![](/img/trans.png)
[英]What's the difference between a name array and the first element of the array in C?
[英]C Initializer element is not constant [What's the difference between array and variable]
我有以下代碼段
#include <stdio.h>
int a[4];
int b;
struct test {
int *ptr;
int val;
};
struct test test_array[] = {
{
a, //Don't understand here
b //compile error
}
};
int main() {
struct test ha = test_array[0];
ha.ptr[0] = 10;
printf("%d\n", ha.ptr[0]);
return 0;
}
從以下鏈接中,我知道為什么會發生編譯錯誤。 C-初始化元素不是恆定的
但是只是不明白為什么靜態存儲陣列還可以呢?
謝謝
C中全局變量的初始化器必須是常量表達式,而b
不是常量表達式。 (它甚至不是一個const
變量)。相比之下,表達a
是全局數組的第一個元件的地址 a
和全局變量的地址是常量表達式。
要在更高層次上回答你的問題:之間的差別a
和b
為您正在使用的值 b
的,但不是值a
,只有它的地址 。
如前所述,b不是常數。 至於a,變量的內容也不是常量,但是結構中的所有內容就是該數組的地址。 這是恆定的,在編譯時就知道了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.