0

I've used pointers to help create my game of fifteen grid, and now I want to print out the board using 'draw'. The function works to the point that the board prints, but instead of array elements I see the memory address. I've tried dereferencing these pointers a number of different ways, but can't fix it.

Any help would be much appreciated.

//Grid variable declaration
int grid[d-1][d-1];

//Pointer declaration
int *p = &grid[0][0];  

//Call of draw function
draw(d, *p);

void draw(k, pgrid)
{
    // TODO
     for (int x = 0; x < k; x++)
    {
        for (int y = 0; y < k; y++)
        {
            if (pgrid < 10)
                printf("%d ", *pgrid);
            else if (pgrid >= -1)
                printf("%2d ", *pgrid);
            else 
                printf("%2s ", "_");
            pgrid++;            
        }
        printf("\n");
    }
}
1

This is not a typical usage for pointers. You don't really need to use pointers here at all. If grid is declared as a global variable, you may directly write something like this within draw() to print its values

for (int row = 0; row < d - 1; row++)
{
    for (int column = 0; column < d - 1; column++)
    {
        printf("%d\t", grid[row][column]);
    }
    printf("\n");
}

Also, your parameters' types are missing in draw()'s signature. If you don't want draw() to return anything and to receive an int and a 2D int array, you may write something like

void draw(int x, int array[][columns])
{
     // do something
}

where columns is a literal value that represents the number of columns in array.

Arrays also decay to pointers. This means that when you use the name of an array variable by itself (e.g., grid), this can be treated as a pointer to the first element in the array.

But since this is a multi-dimensional array (specifically a 2D-array), the first element in grid (i.e., grid[0]) is another array itself. So you may also write something like

void draw(int x, int *(array)[columns])
{
    // do something
}
| improve this answer | |
  • Thank you! I knew there had to be an easier way. – user1645 Jul 7 '14 at 1:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .