簡體   English   中英

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和全局變量的地址常量表達式。

要在更高層次上回答你的問題:之間的差別ab為您正在使用的 b的,但不是值a ,只有它的地址

如前所述,b不是常數。 至於a,變量的內容也不是常量,但是結構中的所有內容就是該數組的地址。 這是恆定的,在編譯時就知道了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM