0

I'm kind of stuck since i'm trying to do what is in the title. instinctively i would do this :

size = 10 //(for example)
int** pieces[10][10];
pieces* = (int*)malloc(sizeof(int*)*size);

But it doesn't even compile.

Do you have any idea ? Thank you !

Strauss
  • 43
  • 6

2 Answers2

1

In order not to mix up the syntax with "array of pointers", you need to do this:

int (*pieces) [10][10]; // pointer to int [10][10]

And then to allow convenient access with syntax pieces[i][j] rather than (*pieces)[i][j], drop the outer-most dimension:

int (*pieces) [10]; // pointer to int[10], the type of the first element of a int[10][10].

Allocate with

pieces = malloc( sizeof(int[10][10]) );
...
free(pieces);

Details here: Correctly allocating multi-dimensional arrays

Lundin
  • 174,148
  • 38
  • 234
  • 367
-1

you are trying to make a pointer to a pointer to an array of 2d of ints. you need to delete the bracktes ([10][10]) you should allocate an array of pointers for the rows pieces = (int**)malloc(sizeof(int*)*size); and then allocate for each column with a loop like this:

int i;

for (i = 0; i < size; i++)
    pieces[i] = (int*)malloc(sizeof(int));

afterwards you will need to free all the column allocations and then first row allocation of pieces.

Gilad
  • 315
  • 1
  • 2
  • 8
  • 2
    Please do not recommend people make arrays like this. It has become popular in amateur circles, but it is bad for performance (due to requiring multiple pointer loads and other effects) and is a nuisance to manage. In many C implementations, an m×n array of `int` can be allocated simply with `int (*a)[n] = malloc(m * sizeof *a);`. In implementations without support for variable length arrays, space can be allocated using `int *a = malloc(m * n * sizeof *a);` and then used with manual subscript calculations. – Eric Postpischil Oct 30 '20 at 12:05