简体   繁体   中英

C pointer to 2d array

So i'm creating a loop which can create a 3x3 board by setting the elements of a [3][3] array to enum EMPTY. While debugging, I can see that the program sets the first three elements of the array correctly before getting a memory access violation error, so I know this is a problem with the address of the second row of the array (when the 'i' variable turns from 0 to 1). How do I solve this? pointers are still a bit confusing to me tbh.

int main(void)
{
    int board[3][3] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    int* p = &board;


    create_board(p);
    print_board(p);

    return 0;
}
void create_board(int *board)
{
    for (int i = 0; i < 3; ++i)
    {

        for (int k = 0; k < 3; ++k)
        {
            (&board)[i][k] = EMPTY;

        }
    }

    return;
}

Your code has many issues. Arrays in C do not hold any information about their sizes.

The easiest way is to use a pointer to the array:

void create_board(size_t rows, size_t cols, int (*board)[rows])
{
    for (size_t i = 0; i < rows; ++i)
    {

        for (size_t k = 0; k < cols; ++k)
        {
            board[i][k] = EMPTY;
        }
    }
}

and main

int main(void)
{
    int board[3][3];
 
    create_board(3,3, board);
    print_board(3,3,board);
    return 0;
}

Similar way you can write print_board function:

void print_board(size_t rows, size_t cols, int (*board)[rows])
{
    for (size_t i = 0; i < rows; ++i)
    {
        for (size_t k = 0; k < cols; ++k)
        {
            printf("[%zu][%zu] = %d\t", i, k, board[i][k]);
        }
        printf("\n");
    }
}

Your code is invalid. The compiler should issue a message that there are used incompatible pointer types in this declaration

int* p = &board;

The initializing expression has the type int ( * )[3][3] while the initialized object has the type int * .

The function can be declared either like

void create_board( int ( *board )[3], size_t n )
{
    for (size_t i = 0; i < n; ++i)
    {

        for (size_t k = 0; k < 3; ++k)
        {
            board[i][k] = EMPTY;

        }
    }
}

and called like

int ( *p )[3] = board;
create_board( p, 3 );

Or if your compiler supports variable length arrays then like

void create_board( size_t m, size_t n, int ( *board )[n] )
{
    for (size_t i = 0; i < m; ++i)
    {

        for (size_t k = 0; k < n; ++k)
        {
            board[i][k] = EMPTY;

        }
    }
}

and called like

int ( *p )[3] = board;
create_board( 3, 3, p );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM