动态分配的二维数组 [英] Dynamically allocated 2 dimensional array

查看:150
本文介绍了动态分配的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过动态地分配建立二维数组。我的问题是,是有可能,它的第一个维度将需要100个值,那么第二个方面将取决于我的问题,采取的值变量?如果有可能,那么我将如何访问它?我怎么知道第二个维度的边界?

I am trying to build two dimensional array by dynamically allocating. My question is that is it possible that its first dimension would take 100 values, then second dimension would take variable amount of values depending on my problem? If it is possible then how I would access it? How would I know the second dimension's boundary?

推荐答案

(见code中的评论)

因此,你会得到一个数组,如下所示:

这里是code:

// 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);        
}
*/
}

PS 我已经把那个验证为注释,以便强调的的code的主要部分。

PS I've put that verifications into comments in order to highlight the main parts of the code.

这篇关于动态分配的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆