Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I work with dynamic multi-dimensional arrays in C?

Tags:

arrays

c

dynamic

Does someone know how I can use dynamically allocated multi-dimensional arrays using C? Is that possible?

like image 802
rpf Avatar asked May 27 '09 20:05

rpf


People also ask

How do multidimensional arrays work C?

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

How does a dynamic array work in C?

Dynamic arrays are resizable and provide random access for their elements. They can be initialized with variable size, and their size can be modified later in the program. Dynamic arrays are allocated on the heap whereas VLAs are allocated on the stack.

How do you use dynamic arrays?

Dynamic arrays in C++ are declared using the new keyword. We use square brackets to specify the number of items to be stored in the dynamic array. Once done with the array, we can free up the memory using the delete operator. Use the delete operator with [] to free the memory of all array elements.

Can C language handle multidimensional arrays?

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];


1 Answers

Since C99, C has 2D arrays with dynamical bounds. If you want to avoid that such beast are allocated on the stack (which you should), you can allocate them easily in one go as the following

double (*A)[n] = malloc(sizeof(double[n][n])); 

and that's it. You can then easily use it as you are used for 2D arrays with something like A[i][j]. And don't forget that one at the end

free(A); 

Randy Meyers wrote series of articles explaining variable length arrays (VLAs).

like image 195
Jens Gustedt Avatar answered Nov 15 '22 12:11

Jens Gustedt