c - C 结构中奇怪的 const char 指针成员初始化

标签 c

libwebsockets库示例有一个类型为 struct lws_http_mount 的变量已初始化 here结构 lws_http_mount 已声明 here 。为了方便起见,下面是其声明和定义的片段。

struct lws_http_mount {
   const struct lws_http_mount *mount_next;
   const char *mountpoint;
   const char *origin;
   const char *def;
   const char *protocol;
   const struct lws_protocol_vhost_options *cgienv;
   const struct lws_protocol_vhost_options *extra_mimetypes;
   const struct lws_protocol_vhost_options *interpret;
   int cgi_timeout;
   int cache_max_age;
   unsigned int auth_mask;
   unsigned int cache_reusable:1;
   unsigned int cache_revalidate:1;
   unsigned int cache_intermediaries:1;
   unsigned char origin_protocol;
   unsigned char mountpoint_len;
   const char *basic_auth_login_file;
   void *_unused[2];
};

static const struct lws_http_mount mount_localhost1 = {
   /* .mount_next */           NULL,
   /* .mountpoint */           "/",
   /* .origin */               "./mount-origin-localhost1",
   /* .def */                  "index.html",
   /* .protocol */              NULL,
   /* .cgienv */                NULL,
   /* .extra_mimetypes */       NULL,
   /* .interpret */             NULL,
   /* .cgi_timeout */           0,
   /* .cache_max_age */         0,
   /* .auth_mask */             0,
   /* .cache_reusable */        0,
   /* .cache_revalidate */      0,
   /* .cache_intermediaries */  0,
   /* .origin_protocol */       LWSMPRO_FILE,
   /* .mountpoint_len */        1,
   /* .basic_auth_login_file */ NULL,
}

该结构体的成员mountpointconst char*类型。它已在变量 mount_localhost1 中初始化为 "\"。在此结构中为其成员mountpoint分配的实际字符数组大小是多少?

我只知道结构内部的 char 数组成员声明应该作为 char mountpoint[string_length] 而不是 const char* mountpoint

最佳答案

字符串文字(字符数组)"/" 在内存中创建,常量字符指针mountpoint 使用该内存的地址进行初始化。

没有“在此结构内分配的实际字符数组大小”。

这与初始化局部变量没有什么不同,例如:

const char *mountpoint = "/";

变量(const char *)的大小只是指针的大小。实际的字符串(字符数组)为 somewhere else ,与字符指针本身无关。

关于c - C 结构中奇怪的 const char 指针成员初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57487463/

相关文章:

C 将固定大小的 char 数组与 String 进行比较

Windows 中的 C++ 高精度时间测量

c - C 最佳实践中的项目组织

c - printf() 产生垃圾

c - 使用 STM32 进行 SPI 的 DMA 时数据无效

c - 输出 a = ~a + 2 << 1 ;

c - 在有限制的情况下玩一会儿 - C 编程

c - 当字符串相等时 strcmp 结果为 false

检查所有 malloc 是否受到 NULL 返回保护

c - 传递二维数组之间的区别