Returning a multidimensional array in c
I'm having issues with returning a multidimensional array. I create the array in a function and then modify it in another function. In the main function I want to print out the contents of the array as indicated below but, I am not getting anything to show up in the console.
Any suggestions? Thanks.
//Build the grid array given the number of rows, columns and levels
char ***buildGrid(int numRows, int numCols, int numLevels)
{
char ***levels;
levels = malloc(numLevels *sizeof(char *)); //Contains all levels
int rowIndex, levelIndex;
for (levelIndex = 0; levelIndex < numLevels; levelIndex++)
{
char **level = malloc(numRows * sizeof(char *)); //Contains all rows
for(rowIndex = 0; rowIndex < numRows; rowIndex++)
{
level[rowIndex] = malloc(numCols * sizeof(char)); //Contains all columns
}
levels[levelIndex] = level;
}
return levels;
}
void readGrid(char ***grid)
{
grid = buildGrid(3,3,3);
grid[0][0][0] = 'a';
}
int main (int argc, const char * argv[])
{
char ***gridD开发者_开发技巧ata;
readGrid(gridData);
printf("%c", gridData[0][0][0]); //This does not output anything
return 0;
}
I think you should do
readGrid( &gridData );
and
void readGrid(char**** grid)
{
*grid = buildGrid(3,3,3);
(*grid)[0][0][0] = 'a';
}
Thats because you want to change the contents of gridData
.
Also, define your main as int main(void)
In main, you pass grid pointer by value, and not by address. whenever you want to change the content of a variable, you have to give it's address, otherwise, only it's copy will be changed, so whenever you want to change a char*** gridData;
in another function, the other function should receive a parameter of type char****
and you should call it by readGrid(&gridData)
etc.
In main() grid is undeclared, so your code won't even compile. You probably meant gridData.
But then gridData is uninitialized and dereferencing it results in undefined behavior.
Moreover, "void main()" is undefined behavior too, so is not checking return value of malloc() and dereferencing it.
精彩评论