I want to make a 2 dimensional array in C.
I know 1 way to make it like this.
#include <stdlib.h>
void my_func(int **arr)
{
printf("test2: %d\n", arr[0][1]);
}
int main(void)
{
const int row = 3;
const int col = 4;
int **arr = (int **)malloc(sizeof(int *) * 3);
arr[0] = (int *)malloc(sizeof(int) * 4);
arr[1] = (int *)malloc(sizeof(int) * 4);
arr[2] = (int *)malloc(sizeof(int) * 4);
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[0][3] = 4;
arr[1][0] = 3;
arr[1][1] = 4;
arr[1][2] = 5;
arr[1][3] = 6;
arr[2][0] = 5;
arr[2][1] = 6;
arr[2][2] = 7;
arr[2][3] = 8;
printf("test1: %d\n", arr[0][1]);
my_func(arr);
}
In this case, the array can be passed to the function well as an argument. But it's not that pretty. If the array has lots of values (e.g 20*20), I need to type every single value line by line.
So I searched it and found out a way to make an array like this.
#include <stdio.h>
void my_func(int **arr)
{
printf("test2: %d", arr[0][1]);
}
int main(void)
{
const int row = 3;
const int col = 4;
int arr[row][col] = {
{1,2,3,4},
{3,4,5,6},
{5,6,7,8}
};
printf("test1: %d", arr[0][1]);
my_func(arr);
}
It's concise and don't make me exhausted. But something is wrong when array is passed to a function. And when compiling, there is a warning as below
test_2D_array.c:20:11: warning: incompatible pointer types passing 'int [3][4]' to
parameter of type 'int **' [-Wincompatible-pointer-types]
my_func(arr);
^~~
test_2D_array.c:3:20: note: passing argument to parameter 'arr' here
void my_func(int **arr)
^
1 warning generated.
and Even the function can't access the array argument. There is a segmentation fault.
So I want to know the best way to make array which can be passed toany function as an argument and less exhausting than my first code.
Thank you for reading.