LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Allocate memory for 2D arrays

What is the way to dynamic allocate memory for 2D arrays?
0 Kudos
Message 1 of 5
(4,262 Views)
Use calloc() or malloc() to dynamically allocate memory for arrays.
Arrays in C are stored with no overhead: there are no markers to separate elements, rows, columns, etc. An array is just a contigous block of data.
To use calloc(), you need to know the number of elements and the size of each element. calloc() initializes all memory to 0.
To use malloc(), you need to know the total size of the array. malloc() allocates the memory, but doesn't initialize it.
In either case, the sizeof() function can help.
If you're creating a 10 by 20 array of integers, you have 10*20 = 200 elements. Each element has a size of sizeof(int).
calloc() and malloc() both return a pointer to void. You need to cast it to the type you're using.

int *myPointer;
myPointer = (int *) calloc( sizeof(int), 200);
// or
myPointer = (int *) malloc( sizeof(int) * 200);
//
free(myPointer); //when you're done with the array

To treat the allocated memory as a two dimensional array, you'll need to do some pointer math.
See the attached example. See some additional examples here.
0 Kudos
Message 2 of 5
(4,249 Views)
If you want the ease of use and readability of a real 2-d array, you can take the extra step of allocating a second array of pointers into the first array which can then be used like a static 2-d array.

ex:

int i, numRows = 5, numColumns = 15;
int **array = malloc (numRows * sizeof (int *));
int *memory = malloc (numRows * numColumns);

for (i = 0; i < numRows; ++i)
{
array[i] = memory + i * numColumns;
}

// this allows this usage
array[0][0] = 3;
array[numRows - 1][numColumns - 1] = 4;

free (array);
free (memory);


An alternative to this is to allocate "numRows" arrays of "numColumns" elements but this causes the managing code to be a little messier.

Hope this helps,

Alex
0 Kudos
Message 3 of 5
(4,241 Views)
Oops!

int *memory = malloc (numRows * numColumns);

should actually be

int *memory = malloc (numRows * numColumns * sizeof (int));

-alex
0 Kudos
Message 4 of 5
(4,242 Views)
Hi!

Sorry, but it does not work.
Especially the "// this allows this usage" section.

Here it is what could meet my expectation.
{
int i, numRows = 17, numColumns = 5;
char **array;

array = malloc ( numRows * sizeof(char*));

for (i = 0; i <= numRows; ++i)
array[i] = malloc (numColumns);
}
Whit this the "// this allows this usage" works fine.
0 Kudos
Message 5 of 5
(4,206 Views)