How can I use dynamic 2d array in c

I tried to create a 5x5 int dynamic array

int **data=malloc(5*5);

But I get a segmentation error when trying to access it.

+4
source share
5 answers

You need to allocate memory for the 2d array that you want to do (which I think you understand). But first, you will need to allocate space for pointers, where you will store the strings of the 2D array.

int **data=(int**)malloc(sizeof(*data)*5); //Here 5 is the number of rows

Now you can allocate space for each row.

for(int r=0;r<5;r++){
  data[r]=(int*)malloc(sizeof(**data)*5);//here 5 is the width of the array
}

If you need a continuous block of memory for the entire array, you can allocate one dimensional array of size 25 and access it as data[r*5+c].

PS: sizeof(*data) sizeof(**data) sizeof(int*) sizeof(int), *

PS: ++, malloc (. ).

+7

, 5x5 = 25 :

int *data = malloc(5*5*sizeof(*data));

2d- 5x5

int **data = malloc(5*sizeof(*data));
for (int i=0; i<5; ++i)
    data[i] = malloc(5*sizeof(**data));
+4

. - :

int ( *data )[5] = malloc( 5 * 5 * sizeof( int ) );

.

- , , .

int **data = malloc( 5 * sizeof( int * ) );
for ( size_t i = 0; i < 5; i++ )
{
    data[i] = malloc( 5 * sizeof( int ) );
}

6 : 5 .

,

free( data );

for ( size_t i = 0; i < 5; i++ ) free( data[i] );
free( data );
+3

2D- (a[i][j]), , , :

int (*data)[5] = malloc( sizeof *data * 5 );

, 1:

size_t rows, cols;
...    
int (*data)[rows] = malloc( sizeof *data * cols );2

VLA, , :

size_t rows, cols;
...
int **data = malloc( sizeof *data * rows );
if ( data )
{
   for ( size_t i = 0; i < rows; i++ )
   {
     data[i] = malloc( sizeof *data[i] * cols );
   }
}

, (, , ). , .

, , 1D- (a[i * rows + j]):

int *data = malloc( sizeof *data * rows * cols );


1. VLA C99, C2011. post-C99, __STDC_NO_VLA__, VLA.

2. - , sizeof *data ; sizeof , VLA, . data - , undefined. , , , , , .
0

:

int ** squaredMatrix;
int szMatrix=10;
squaredMatrix= (int**)malloc(szMatrix*sizeof(int*));

to create 2d arrays you must consider them as one array, which each block is an array again. enter image description here

for example, in the figure above, the blue blocks form an array that each blue block points to an array (every 4 green blocks in a row are an array, and the blue blocks in a column are the main array)

-1
source

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


All Articles