[英]Can someone explain how the code works?
#include <stdio.h>
#include <stdlib.h>
typedef int * pinax;
int main()
{
pinax *A;
int size,i,j;
int *cols;
printf ("How many sets of numbers: ");
scanf ("%d",&size);
cols = (int*) malloc (size*sizeof(int));
A = (pinax *) malloc (size * sizeof(pinax));
//Above part i cant understand
for (i=0;i<size;i++)
{
printf ("How many numbers in set %d: ",i+1);
scanf("%d",&cols[i]);
A[i] = malloc (cols[i]*sizeof(int));
printf ("Give %d numbers seperated by space or newline: ",cols[i]);
for (j=0;j<cols[i];j++)
scanf ("%d",&A[i][j]);
}
for (i=0;i<size;i++) // First dimension is not stable
{
for (j=0;j<cols[i];j++) // Second dimension is not stable
printf ("%d ",A[i][j]);
printf ("\n");
}
return 0;
}
這是我 uni 的筆記,它基本上創建了一個動態 2D 數組。我無法理解它在我來的評論上方的工作原理。最后 2 條評論是我的教授,我真的不明白為什么最后 2 條 for 循環中的維度是穩定的。有人可以解釋我嗎?
在許多編譯器中,確實需要在編譯時間之前預定義數組大小。 在你的情況下,你真的不知道你需要處理多少組數字(因為數字來自`scanf,這是用戶輸入),所以有兩種方法:擁有一個如此大的數組保證用戶輸入永遠不會超過數組的大小(有時很難甚至不可能),或者為數組動態分配一些內存。
在這種情況下,實現了第二種方式。 malloc 函數為數組分配一些內存(因此得名)。
基本上, cols = (int*) malloc (size*sizeof(int));
與說int cols[size];
幾乎相同int cols[size];
不同之處在於第二種方式不是正確的方式並且在許多編譯器中不起作用,因為size
是一個變量。
*注意:動態分配的內存與靜態分配的內存之間還有另一個區別,這就是分配內存的地方。 如果你有興趣,你可以自己閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.