Another way to malloc a 2D array?

I want to declare a 2d array using malloc. When searching the Internet, all websites say to declare an int ** pointer, and then use malloc to first allocate individual pointers to 1d arrays, and then use malloc again to allocate space for individual ints. I doubt that an array declared this way does not hold its elements in contiguous memory addresses. Although the following method uses only one malloc operator and dynamically allocates a 2d array, and all addresses are contiguous if necessary. So, shouldn't the 2d array be dynamically allocated as follows?

#include <stdio.h> int main(){ int (*p)[2] = malloc(3 * sizeof *p); int i; int j; //All addresses printed here are contiguous for(i=0; i<3; i++){ for(j=0; j<2; j++){ printf("%d\t", &p[i][j]); } printf("\n"); } } 
+4
source share
3 answers

So, shouldn't there be a proper way to dynamically allocate a 2d array?

It should , because this approach is the equivalent of declaring an array of “statically assigned” multiple dimensions.

The reason for this is that in this way you get a continuous block of memory that is convenient (you cannot use memset() to pointer to a pointer, right?), And you can still have the compiler do the calculation of the pointer arithmetic and the calculation of the array substring for you (this is also convenient).

By the way, if you need an array with dynamic size, the scope of which is only within the same function, then i. e. you do not need to return it, consider using a VLA (variable length array) with automatic storage duration.

+3
source

Your 2D array is not fully dynamic, as one of its sizes is tied to two elements. (In your specific example, you can use a variable-length array, but in general, you might want to return the array you selected from the function.)

If you want something that syntactically acts like an 2D M × N array to be allocated completely dynamically and uses continuous memory, you can allocate a block of memory elements M * N , and then select an array of M pointers, where each element points to "string" of the block M * N

Q6.16 of the comp.lang.c FAQ has a good diagram and a more detailed explanation of this.

(Well, it is not completely contiguous, since the array of pointers and the block of elements are separate. You can select them together, although this is more difficult, since additional work will be required to ensure proper alignment.)

+1
source

In other words:

include <stdio.h>

include <stdlib.h>

const int MAXX = 10;

const int MAXY = 10;

int main () {

int * p = (int *) malloc ( MAXX * MAXY );

int x = 3;

int y = 4;

* (p + MAXX * x + y) = 12;

printf ("\ n% d", * (p + MAXX * x + y) );

return 0;

}

this is the easiest way to allocate and use a 2d array

0
source

Source: https://habr.com/ru/post/1488934/


All Articles