C 中的锯齿状数组

Jagged arrays in C

我在 C 中寻找锯齿状数组时遇到了这段代码。我发现很难理解自 calloc() 和 malloc() return 指针以来对 calloc 函数进行类型转换的必要性。

int rowNum,colNum,i,j;
int** table;
scanf("%d",&rowNum);

为什么我们要使用指向指针的指针,下面的行是什么 return?

table = (int**)calloc(rowNum+1,sizeof(int*));
for(i=0;i<rowNum;i++)
{

printf("The size of %d row",i+1);
scanf("%d",&colNum);
table[i] = (int*) calloc(colNum+1,sizeof(int));

上一行发生了什么?指针是否指向第i行的基元素?

for(j=1;j<=colNum;j++)
    {
    //reading the elements in the row
    scanf("%d",&table[i][j]);.
    }
    table[i][0] = colNum;

    printf("The size of row [%d]= %d",i+1,table[i][0]);
    }

这里的table指的是什么?

Table 指向动态指针数组的第一个元素。然后我们让每个指针都指向 for 循环内的一个整数数组。

这与 2 Dim 数组的不同之处在于,在矩阵中,所有行的列数都相同。

我们的要求是得到一个锯齿状的数组。取一个 5 列的数组 A 和另一个 4 列的数组 B,如果你将两者组合在不同的行中,你会得到一个锯齿状的数组。

既然我们必须像这样赋值

table=calloc(rowNum+1,sizeof(int*));
//allocate an array of rowNum pointers and save to table
...
table[i] = calloc(colNum+1,sizeof(int));
//Yes it is pointing to the first element of the i-th row

换句话说,每个 table[i] 代表具有可变列数(此处由用户指定)的每一行。

我想这些链接可以帮到你