You have the declaration:
int **array_2d;
This declares
array_2d
as a
pointer to pointer to int
. But then you allocate the array with
array_2d = malloc(sizeof(int) * rows * cols)
. The
malloc()
returns a contiguous block of memory (i.e.
int *
, which is not a
pointer to pointer to int
You have 2 choices:
1) allocate an array of
int *
that is
rows
long, then allocate an array of
int
that is
cols
long for each row
int **array_2d;
array_2d = malloc(sizeof(int*) * rows); for(int i = 0; i < rows; ++i) {
array_2d[i] = malloc(sizeof(int) * cols); }
2) Since you are using ubuntu and GCC you can make use of gnu extensions and dynamically size the array in
print_2d_array()
void print_2d_array(void *ptr, int rows, int cols)
{
int (*array)[rows] = ptr;
for(int = 0; i < cols; ++i)
{
}
}
In this case you don't need to change your allocation of array_2d in
main()