是否可以在c中动态初始化静态变量?

Is it possible to intialise a static variable dynamically in c?

我知道一个静态变量必须用一个常量初始化,因为静态变量的值必须在程序运行前就知道了开始 运行.

所以我们可以说无法使用动态内存分配初始化静态变量,因为这意味着变量将在程序 运行 时初始化.

另外有人可以解释为什么 静态变量 的值必须在 main 启动 运行 之前知道吗?

关于您的标题问题:是否可以在 c 中动态初始化静态变量?答案是否定的。为什么详情如下...

下一个问题的答案:

"So can we say that its not possible to initialize a static variable using dynamic memory allocation..."

是的,我们可以说,因为:

static int *array = calloc(5, sizeof(int)); 

将无法编译,因为初始化元素不是 compile-time 常量。

编译失败的原因在C standard, N1570 paragraph 5.1.2中给出,其中明确指出:

All objects with static storage duration shall be initialized (set to their initial values) before program startup.

但是,将内存动态分配给正确初始化的 static 变量 合法的:

static int *array = NULL; //properly initialized static pointer variable.
...
array = calloc(5, sizeof(int));// legal

最后一个问题的答案:为什么在 main 启动之前必须知道静态变量的值 运行?

可以推导出These statements...

1) Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope. [emphasis mine]

2) Static variables are allocated memory in data segment, not stack segment. See memory layout of C programs for details. [emphasis mine]

3) Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage.[see link for referenced program]

所以,根据定义,因为 static storage scope 的变量需要在程序的 life-time 期间保持局部变量存在,所以感觉在 run-time 开始期间,该内存 space 中存在一个已知值。 (当 main() 开始时 运行。)

您所说的 staticstatic storage duration..

声明一个具有静态存储持续时间的变量实际上意味着在链接期间,链接器将为变量分配存储空间。当链接器负责分配存储时,这意味着变量将在 .rodata 部分(常量)或 ˙.data˙ 或 .bss 部分中有一个地址。

每个静态变量的初始值都写入(硬编码)在可执行文件中,并在调用 main() 函数之前由加载程序简单地复制到正确的地址。这是机制是这些变量必须由常量值初始化(否则它们被零初始化)的原因。