【发布时间】:2019-10-18 22:38:23
【问题描述】:
我需要编写一个函数来创建一个具有不同列数的行的二维数组。这是我尝试过的代码:
#include<stdio.h>
#include<stdlib.h>
// program which allocates and returns a 2D int array full of zeros
int** make_zeros_jagged(int rows, int* array){
// dynamically allocate space for array
int** result = malloc(sizeof(int*)*rows);
if(result==NULL){
printf("allocation error\n");
return NULL;
}
// dynamically allocate space for each row
for(int row=0; row<rows;row++){
// put error handling here
int cols = (sizeof(array[row])/sizeof(int));
printf("\n col: %d\n", cols); // ----------> always returns 1
result[row]=malloc(sizeof(int)*cols);
for(int col=0; col<cols; col++){
result[row][col]= 0;
printf("%d ", result[row][col]);
}
printf("\n");
}
return result;
}
// driver code for building array
int main(void){
// declare and build 2d array
int rows = 3;
int row1[5] ;
int row2[4] ;
int row3[3] ;
int* array[] = { row1, row2, row3 };
int** newarray;
newarray = make_zeros_jagged(3,*array);
return 0;
}
预期的结果应该是
0 0 0 0 0
0 0 0 0
0 0 0
但我的代码返回
0
0
0
我想知道是否应该在函数的参数中包含每行的列数?但我也不知道该怎么做。将列数读入数组?还是我的方法也可以?请帮我解决一下这个。谢谢!
【问题讨论】:
-
sizeof(array[row])==sizeof(int),给定int * array -
您似乎将分配作为堆栈变量和通过
malloc进行分配混为一谈。您当前正在尝试分配两者:静态变量在main内使用int row1[5];并通过函数中的 malloc。你真的想要哪个:malloc-allocated 数组,或者只是指向main中静态大小数组的指针数组? -
@rtoijala OP 使用
rowNarrays 作为 malloc-ed 的“模板”,但无法确定大小。 -
请注意,您不是在创建“二维数组”,也不是“锯齿状”。您正在创建一个指向一维数组的指针数组,其中一维数组的长度不同。
标签: c multidimensional-array jagged-arrays