Simple solution — but no pointer to 2D array
The function should be simply:
#include <stdbool.h>
enum { size = 24 };
extern void change_to_true(bool array[][size], int i, int j);
void change_to_true(bool array[][size], int i, int j)
{
array[i][j] = true;
}
int main(void)
{
bool array[size][size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
array[i][j] = false;
change_to_true(array, i, j);
}
}
}
I'm assuming, of course, that you have a C99 or C2011 compiler. If you're stuck with C89, then you'll have to provide definitions for bool
and true
; the rest does not need to change. I'm not convinced the function call is worth it, compared with the assignment of false
.
Solution using pointer to 2D array
Note that the code above does not, strictly, create a pointer to a 2D array. If you are really, really sure that's what you want, then the notation changes:
#include <stdbool.h>
enum { size = 24 };
extern void change_to_true(bool (*array)[][size], int i, int j);
void change_to_true(bool (*array)[][size], int i, int j)
{
(*array)[i][j] = true;
}
int main(void)
{
bool array[size][size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
array[i][j] = false;
change_to_true(&array, i, j);
}
}
}
There's no benefit to using a formal 'pointer to array' that I can think of, though — not in this context.
Solution using C99 variable length arrays
In C99, you can also use a VLA — variable length array — like this:
#include <stdbool.h>
extern void change_to_true(int size, bool array[][size], int i, int j);
void change_to_true(int size, bool array[][size], int i, int j)
{
array[i][j] = true;
}
int main(void)
{
for (int size = 2; size < 10; size++)
{
bool array[size][size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
array[i][j] = false;
change_to_true(size, array, i, j);
}
}
}
}
Note that the size must precede the array declaration in the function declaration. And yes, you also write this with pointer to array notation (actually, I edited the pointer to array notation code first, then realized that I wanted the simpler version).
Which to use?
Unless you have compelling reasons not mentioned in the question, the first version is the code to use.