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
  • 7
  • "it doesn't even compile" why not? what is the exact error? anyway, this is surely answered 100s of times already. – underscore_d Oct 30 '20 at 11:55
  • `int** pieces[10][10];` You probably either want `int pieces[10][10];` or `int** pieces;` – 001 Oct 30 '20 at 11:56
  • What do you want to make? One 10×10 array of `int`? An n×n array of `int`, where `n` is not known at compile time? Or something else? – Eric Postpischil Oct 30 '20 at 12:01

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
  • 195,001
  • 40
  • 254
  • 396
-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
  • 305
  • 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