簡體   English   中英

數組C的錯誤:可變地修改了錯誤

[英]Error in C for Array: error variably modified

運行代碼時出現此錯誤:

"error: invariably modified 'Square_Toys' at file scope.

在我的代碼頂部全局定義了一個名為NumOfToys ,然后在其后定義數組Toy* Square_Toys[NumOfToys] NumOfToys取決於用戶輸入的內容,因此我無法事先定義數組的大小:(。是否有人建議我如何擺脫此錯誤?

int NumOfToys; <------- This is entered through the user running the programin the terminal
struct toy * Square_Toys[NumOfToys];

在這種情況下,您不能使用直接數組。 可變長度數組只能在本地范圍內聲明。 即,如果數組大小是運行時值,則無法在文件范圍內聲明該數組。 具有靜態存儲持續時間的所有陣列應具有編譯時大小。 沒有辦法解決。

如果必須在文件范圍內聲明數組(順便說一句,為什么?),則必須使用指針代替,並使用malloc手動分配內存,如

int NumOfToys;
struct toy **Square_Toys;

int main()
{
  ...
  /* When the value of `NumOfToys` is already known */
  Square_Toys = malloc(NumOfToys * sizeof *Square_Toys);
  ...
  /* When you no longer need it */
  free(Square_Toys);
  ...
}

另一種選擇是停止嘗試使用文件作用域變量,而改用本地數組。 如果數組的大小不會過大,則可以在本地范圍內使用“可變長度數組”。

第三種選擇是丑陋的混合方法:聲明全局指針,但使用本地VLA分配內存

int NumOfToys;
struct toy **Square_Toys;

int main()
{
  ...
  /* When the value of `NumOfToys` is already known */
  struct toy *Local_Square_Toys[NumOfToys];
  Square_Toys = Local_Square_Toys;
  ...
}

但這只是出於說明目的。 這很丑。

全局數組的大小應為常數,因為編譯器需要在編譯時就知道它。 如果需要動態數組,請在運行時使用malloc分配它:

Toy **Square_Toys;

void foo(void) {
  Square_Toys = malloc(NumOfToys * sizeof(Toy*));

  // do stuff here

  free(Square_Toys);
}

NumOfToys取決於用戶輸入的內容,因此我無法預先定義數組的大小

您可以為數組動態分配空間,也可以使用VLA。 對於VLA,用戶輸入后NumOfToys聲明在你的陣列main

printf("Enter number of toys: ");
scanf("%d", &NumOfToys);

struct toy * Square_Toys[NumOfToys];    

暫無
暫無

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

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