我正在尝试通过动态分配来构建二维数组。我的问题是它的第一个维度是否有可能采用 100 个值,然后第二个维度会根据我的问题采用可变数量的值?如果可能的话,我将如何访问它?我怎么知道第二个维度的边界?
最佳答案
(看代码中的注释)
结果你会得到一个像下面这样的数组:
// Create an array that will contain required variables of the required values
// which will help you to make each row of it's own lenght.
arrOfLengthOfRows[NUMBER_OF_ROWS] = {value_1, value_2, ..., value_theLast};
int **array;
array = malloc(N * sizeof(int *)); // `N` is the number of rows, as on the pic.
/*
if(array == NULL) {
printf("There is not enough memory.\n");
exit (EXIT_FAILURE);
}
*/
// Here we make each row of it's own, individual length.
for(i = 0; i < N; i++) {
array[i] = malloc(arrOfLengthOfRows[i] * sizeof(int));
/*
if(array[i] == NULL) {
printf("There is not enough memory.\n");
exit (EXIT_FAILURE);
}
*/
}
关于c - 动态分配的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19920452/