[英]Scanning to 2d array and then passing it to function - C
如果將函數分配為一維數組,然后將其傳遞給函數,則程序將出現分段錯誤。 它是為2D數組構建的。 問題是,我找不到如何分配2d數組以及如何將其正確傳遞到函數中。 希望大家能清楚解釋。 如果您知道出了什么問題,請嘗試引導我采用正確的方法進行修復。 非常感謝。 這是代碼:
int main()
{
int i, j, size;
scanf("%d", &size);
int *a;
//here i try to allocate it as 2d array
*a = (int *)malloc(size * sizeof(int));
for (i=0; i<size; i++)
{
a[i] = (int *)malloc(size * sizeof(int));
}
//here i scan value to 2d array
for (i = 0; i < size; i++)
for (j = 0; j < size; j++){
scanf("%d", &a[i][j]); }
//here i pass array and size of it into function
if (is_magic(a,size))
函數頭看起來像:
int is_magic(int **a, int n)
這不起作用:
*a = (int *)malloc(size * sizeof(int));
因為a
具有類型int *
所以*a
具有類型int
,所以分配指向該類型的指針沒有意義。 您還試圖取消引用尚未初始化的指針,從而調用未定義的行為 。
您需要將a
定義為int **
:
int **a;
並在第一次分配時直接分配給它,使用sizeof(int *)
作為元素大小:
a = malloc(size * sizeof(int *));
還要注意, 您不應該轉換malloc
的返回值 。
掃描二維陣列? 對於那些你需要采取a
為int**
的類型不只是int*
型。 例如
int **a = malloc(NUM_OF_ROW * sizeof(int*)); /* allocate memory dynamically for n rows */
然后為每行分配內存,例如
for (i=0; i<size; i++){
a[i] = malloc(NUM_OF_COLUMN * sizeof(int)); /* in each row how many column, allocate that much memory dynamically */
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.