[英]Variable array declaration
考慮下面的C代碼:
#include<stdio.h>
int main()
{int n,i;
scanf("%d",&n);
int a[n]; //Why doesn't compiler give an error here?
}
當編譯器最初不知道時,如何聲明數組?
如果直到編譯時仍不知道數組的確切大小,則需要使用動態內存分配。 在C標准庫中,有用於動態內存分配的函數:malloc,realloc,calloc和free。
這些功能可以在<stdlib.h>
頭文件中找到。
如果要創建數組,請執行以下操作:
int array[10];
在動態內存分配中,您可以執行以下操作:
int *array = malloc(10 * sizeof(int));
您的情況是:
int *array = malloc(n * sizeof(int));
如果分配內存位置,請不要忘記取消分配:
if(array != NULL)
free(array);
內存分配是一個復雜的主題,我建議您搜索主題,因為我的回答很簡單。 您可以從以下鏈接開始:
https://www.programiz.com/c-programming/c-dynamic-memory-allocation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.