I am trying to write data into a variable length two dimensional array and my program keeps seg-faulting when I call myfunc but it works fine when I try to perform the same manipulation outside of a function. I can tell that the issues is that the address pointed to at array[0] doesn't equal the address pointed to at data[0]. Can someone advise me as to the root cause of this issue and proper way to rewrite myfun.
void myfun(unsigned char **array){
printf("array = %p, array[0] = %p\n", array, array[0]);
//This line below causes a segfault
strcpy(array[0], "Position0");
}
int main(void) {
int row = rand() % 5 + 1; // random number between 1-5
int col = rand() % 10 + 20; // random number between 20-29
unsigned char data[row][col];
printf("data = %p, data[0] = %p\n", data, data[0]);
//This function call causes a segfault
myfun(data);
printf("%s\n", data[0]);
//This works
strcpy(data[1], "Position1");
printf("%s\n", data[1]);
return 0;
}
myfun, but not when you perform it outside the function; the comment in your code says the opposite.char[x][y]is incompatible withchar**, and you should have listened to that warning, because it's true. If it didn't warn you, learn how to enable warnings.