0

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 ***gridData;

    readGrid(gridData);

    printf("%c", gridData[0][0][0]); //This does not output anything

    return 0;
}
2
  • Gasp! When you get to *** or **** you are probably not looking in the right direction! Commented Apr 2, 2011 at 16:35
  • It is suppose to be a 3D array. How would you suggest in doing it otherwise. Commented Apr 2, 2011 at 16:42

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

On a sidenote. You should also write printf("%c\n", gridData[0][0][0]); to make the output more clear.
2

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.

Comments

0

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.

1 Comment

Sorry yes, printf should be gridData.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.