I have a 3D array declared in main() function:
char currentPositions[5][6][2];
And i want to modify this array using another function:
SetDefaultPositions(currentPositions);
This function looks something like this:
void setDefaultPositions(char positions[5][6][2]){
char defaultPositions[5][6][2] = {
{"()", "()", "..", "..", "..", ".."},
{"/\\", "/\\", "/\\", "/\\", "/\\", "/\\"},
{"..", "..", "..", "..", "..", ".."},
{"/\\", "/\\", "/\\", "/\\", "/\\", "/\\"},
{"..", "..", "..", "..", "..", ".."}
};
positions = defaultPositions;
}
I tried using pointers but it keeps telling me things like this: expected 'char (**)[2]' but argument is of type 'char (*)[6][2]' warning: passing argument 1 of 'setDefaultPositions' from incompatible pointer type [-Wincompatible-pointer-types] Or no errors, but printing currentPositions showed that it was empty. I understand nothing, I also tried some solutions from web but I can't find someone with similar problem. It's school project and I am not allowed to use global variables.
You can't pass an array to a C function. It decays to a pointer.
You can do it like this:
#include <stdio.h>
#include <stdlib.h>
void setDefaultPositions(size_t size, char positions[5][6][2]){
char defaultPositions[5][6][2] = {
{"()", "()", "..", "..", "..", ".."},
{"/\\", "/\\", "/\\", "/\\", "/\\", "/\\"},
{"..", "..", "..", "..", "..", ".."},
{"/\\", "/\\", "/\\", "/\\", "/\\", "/\\"},
{"..", "..", "..", "..", "..", ".."}
};
memcpy(positions, defaultPositions, size);
}
int main(void)
{
char arr[5][6][2];
setDefaultPositions(sizeof arr, arr);
for(int j = 0; j < 5; j++) {
for(int i = 0; i < 6; i++) {
printf("%.2s ", arr[j][i]);
}
printf("\n");
}
return 0;
}
Program output:
() () .. .. .. ..
/\ /\ /\ /\ /\ /\
.. .. .. .. .. ..
/\ /\ /\ /\ /\ /\
.. .. .. .. .. ..
Bear in mind that the array elements are not strings – they have no terminator.