ncc1701e
ncc1701e

Reputation: 13

Accessing elements in a 2D array in C

I am writing a program that passes a 2D char array into a function for printing. However, when I try to access elements in the 2D array for printing, I can't. This problem does not occur when I place the printing loops and statements in the main() function, only if the array is passed.

Can someone help explain?

void disp_array(char* array)
{
    for (int i = 0; i < SIZE; i++)
    {
        for (int j = 0; j < SIZE; j++)
        {
            printf("%c", array[i][j]);
        }
        printf("\n");
    }
}

Attached is my code: the j in the printf statement is highlighted with an error:

E0142: "expression must have pointer-to-object type but it has type int"

Upvotes: 0

Views: 576

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

The function declaration is wrong.

As the parameter has the type char * then the expressions array[i] yields a scalar object of the type char that is promoted to the type int due to the integer promotions to which you may not apply the subscript operator as you are trying to do array[i][j]. So the compiler issues the error message

E0142: "expression must have pointer-to-object type but it has type int"

The function should be declared like

void disp_array(char array[][SIZE], int n )
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < SIZE; j++)
        {
            printf("%c", array[i][j]);
        }
        printf("\n");
    }
}

or like

void disp_array(char (*array)[SIZE], int n )
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < SIZE; j++)
        {
            printf("%c", array[i][j]);
        }
        printf("\n");
    }
}

The parameter having the array type char[SIZE][SIZE] is implicitly adjusted by the compiler to the type char ( * )[SIZE]. That is the function does not know how many elements of the type char ( * )[SIZE] exist. So you need to specify the number of elements explicitly. Try always to define a more general function.

And along with the array you need to pass the number of rows in the array. For example

disp_array( array, SIZE );

If the array contains strings then the function definition will look like

void disp_array(char (*array)[SIZE], int n )
{
    for (int i = 0; i < n; i++)
    {
        puts( array[i] );
    }
}

Upvotes: 1

Related Questions