c - 动态分配的二维数组

标签 c multidimensional-array dynamic-arrays dynamic-allocation

我正在尝试通过动态分配来构建二维数组。我的问题是它的第一个维度是否有可能采用 100 个值,然后第二个维度会根据我的问题采用可变数量的值?如果可能的话,我将如何访问它?我怎么知道第二个维度的边界?

最佳答案

(看代码中的注释)

结果你会得到一个像下面这样的数组:

enter image description here

// 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/

相关文章:

c - 读取 double 据类型后无法读取字符串

python - reshape numpy ndarray

C++ 矩阵到动态二维数组

excel - 如何在 Excel 中将 SUM 函数与(新)动态数组一起使用

c++ - 如何在动态数组中访问和使用动态数组

将 char* 转换为 char**

C:计算出的机器 epsilon 与 limit.h 不同

c++ - cppsqlite3中的sqlite3的sqlite3_exec是什么(如果有的话)?

ruby-on-rails - 数组到 XML -- Rails

Javascript 多级 JSON 对象数组 - 如何访问第二级或更高级别的键值对