小编use*_*091的帖子

C 存储大小不是常数...为什么?

这是简单的示例程序

#include <stdio.h>
#include <string.h>

const char *hello_string = "Hello";

int main(void)
{
char *world_string = " World";
static char hello_world[strlen(hello_string)+strlen(world_string)];
strcpy(&hello_world[0], hello_string);
strcat(&hello_world[0], world_string);
printf("%s\n", hello_world);
return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器输出:

test.c: In function ‘main’:
test.c:9:13: error: storage size of ‘hello_world’ isn’t constant
static char hello_world[strlen(hello_string)+strlen(world_string)];
            ^
Run Code Online (Sandbox Code Playgroud)

我意识到在这种情况下完全无用和不必要地使用“静态”会导致错误,并且将其删除后,事情将可以正常编译。这只是一个简单的例子来说明我的问题。

我不明白的是为什么当“hello_string”被声明为const char *时,存储大小不是一个常量,并且它的大小在执行过程中不会改变。这只是编译器不够聪明不知道这一点的一个例子吗?

c size storage constants

7
推荐指数
2
解决办法
1万
查看次数

标签 统计

c ×1

constants ×1

size ×1

storage ×1