For my program I need to pass a 2D array of pointers to a function in a separate file. I\'ve written a similarly-syntaxed file below:
#include
#
if you pass an array to a function, you have to specify the size of the inner array, in your case, instead of void setFirst(card_t *cards[][])
, you should specify void setFirst(card_t *cards[][5])
.
Why do you need to specify it and not the size of the first dimension?
Since cards is an array of array of card_t pointers, if you want to get to cards[1][0], the compiler will need to know how much to add to the pointer cards
- cards is declared: card_t *cards[5][4]
it will need to add 4 * sizeof(*card_t)
to get to cards[1][0], but if cards is declared: card_t *cards[5][5]
it will need to add 5 * sizeof(*card_t)
to get to cards[1][0].
Only the first index is optional. You should definitely mention the second index, because a two dimensional array decays to a pointer to 1d array.
void setFirst(card_t *cards[][5]) {
// ^ Newly added
// ..
}
Also make sure that the pointers are pointing to valid memory locations. Else dereferencing leads to segmentation faults. BTW, is there any reason to have a two dimensional array with pointers. I think you are just complicating the program.
To achieve something similar to what you are trying C99 has variable length arrays. These come particularly handy in function definitions:
void setFirst(size_t n, size_t m, card_t *cards[n][m]) {
...
}
Observe that you have to have the size parameters known at the moment of the array declaration, so you'd have to put them in front.
As has been mentioned, to pass a 2d array to a function, you need to have every dimension but the first declared. However, you can also just pass the pointer, as follows. Note that you should always (unless the array dimension is completely fixed and the function that operates on the array only operates within the array's dimension) pass the length of each array, too.
void setFirst(card_t ***cards, size_t n, size_t m) {
if (n > 0 && m > 0) {
cards[0][0]->state = 1;
}
}
Because referencing an array via code[0][0]
is the same as *(*(code+0)+0*m)
, you can pass two pointers instead of array dimensions.