I practice the 2D dynamic array with reference to the URL below: https://thispointer.com/allocating-and-deallocating-2d-arrays-dynamically-in-c-and-c/
My code:
#include <stdio.h>
#include <stdlib.h>
int** create_2d_arr(int row_size,int colum_size)
{
int** array = (int**)malloc(sizeof(int*)*row_size);
for (int i = 0; i < row_size; i++)
array[i] = (int*)malloc(sizeof(int)*colum_size);
return array;
}
void free_2d_arr(int** matrix,int row_size, int colum_size) {
for (int i = 0; i < row_size; i++) {
free(matrix[i]);
}
free(matrix);
}
int main(int argc, char const *argv[])
{
int row=3,cloum=2;
int** arr_2d = create_2d_arr(row,cloum);
arr_2d[0,0]=4;
arr_2d[0,1]=5;
arr_2d[1,0]=6;
arr_2d[1,1]=7;
arr_2d[2,0]=8;
arr_2d[2,1]=9;
for(int i=0;i<row;i++)
for(int j=0;j<cloum;j++)
printf("arr_2d[%d,%d] = %d \n",i,j,arr_2d[i,j]);
free_2d_arr(arr_2d,row,cloum);
return 0;
}
However, there are errors when executing after compilation:
arr_2d[0,0] = 8
arr_2d[0,1] = 9
arr_2d[1,0] = 8
arr_2d[1,1] = 9
arr_2d[2,0] = 8
arr_2d[2,1] = 9
[1] 9300 segmentation fault (core dumped) ./t
Only arr_2d[2,0]=8 arr_2d[2,1]=9 are correct. I don't understand where my code is wrong. Does anyone help me?
renew
thanks for your replies.
but after I modify arr_2d[2,0]=8
to arr_2d[2][0]=8
...
result of printf is
arr_2d[0][0] = -267545984
arr_2d[0][1] = -267545952
arr_2d[1][0] = -267545984
...
warning of compiler
t.c:38:47: warning: expression result unused [-Wunused-value]
printf("arr_2d[%d,%d] = %d \n",i,j,arr_2d[i,j]);
^
t.c:38:40: warning: format specifies type 'int' but the argument has type
'int *' [-Wformat]
printf("arr_2d[%d,%d] = %d \n",i,j,arr_2d[i,j]);
~~ ^~~~~~~~~~~
2 warnings generated.
my compiler is clang,even if I use gcc
=========
Solved
After modify:
printf("arr_2d[%d,%d] = %d \n",i,j,arr_2d[i,j]);
=>
printf("arr_2d[%d,%d] = %d \n",i,j,arr_2d[i],[j]);
It work normally. Thank everyone very much.