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"
CodePudding user response:
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
to which you may not apply the subscript operator as you are trying to do array[i][j]
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");
}
}
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] );
}
}
CodePudding user response:
Although a 1D array in C "decays" to a pointer when used as a function argument, this is not true for a 2D array – which would decay to an array of pointers.
When you have a function that takes a (fixed) array as an argument (whatever its dimensions), just declare that argument as an array – and let the compiler sort out any necessary 'conversion' to pointers.
In your case (I have assumed a value of 4
for SIZE
) just declare the argument for what it is: char array[SIZE][SIZE]
:
#include <stdio.h>
#define SIZE 4
void disp_array(char array[SIZE][SIZE])
{
for (int i = 0; i < SIZE; i ) {
for (int j = 0; j < SIZE; j ) {
printf("%c", array[i][j]);
}
printf("\n");
}
}
int main()
{
char test[SIZE][SIZE] = {
{'a','b','c','d'},
{'e','f','g','h'},
{'i','j','k','l'},
{'m','n','o','p'}
};
disp_array(test);
return 0;
}
In this case, if you have an IDE that will let you see what the actual signature of disp_array
is, it will show (something like) void disp_array(char (*array)[4])
.