Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic allocating array of arrays in C

I don't truly understand some basic things in C like dynamically allocating array of arrays. I know you can do:

int **m;

in order to declare a 2 dimensional array (which subsequently would be allocated using some *alloc function). Also it can be "easily" accessed by doing *(*(m + line) + column). But how should I assign a value to an element from that array? Using gcc the following statement m[line][column] = 12; fails with a segmentation fault.

Any article/docs will be appreciated. :-)

like image 607
hyperboreean Avatar asked Jan 18 '09 21:01

hyperboreean


People also ask

Can you dynamically allocate arrays in C?

We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.

Can we dynamically allocate array?

In addition to dynamically allocating single values, we can also dynamically allocate arrays of variables. Unlike a fixed array, where the array size must be fixed at compile time, dynamically allocating an array allows us to choose an array length at runtime.

Is array dynamic memory allocation in C?

Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime. C provides some functions to achieve these tasks.

Can we use dynamic memory allocation in array?

You can use dynamic memory allocation only for arrays that are local to the MATLAB Function block. You cannot use dynamic memory allocation for: Input and output signals. Variable-size input and output signals must have an upper bound.


1 Answers

The m[line][column] = 12 syntax is ok (provided line and column are in range).

However, you didn't write the code you use to allocate it, so it's hard to get whether it is wrong or right. It should be something along the lines of

m = (int**)malloc(nlines * sizeof(int*));

for(i = 0; i < nlines; i++)
  m[i] = (int*)malloc(ncolumns * sizeof(int));

Some side-notes:

  • This way, you can allocate each line with a different length (eg. a triangular array)
  • You can realloc() or free() an individual line later while using the array
  • You must free() every line, when you free() the entire array
like image 51
jpalecek Avatar answered Sep 24 '22 17:09

jpalecek