Dynamically allocated 2 dimensional array

tryu hjkl picture tryu hjkl · Nov 12, 2013 · Viewed 22.4k times · Source

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?

Answer

yulian picture yulian · Nov 12, 2013

(See the comments in the code)

As a result you'll get an array such like the following:

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