Home > front end >  Trying to pass an array of 2D strings to a function and print it
Trying to pass an array of 2D strings to a function and print it

Time:09-29

New to C, having trouble passing pointers. I am trying to pass this 2D array of pointers which points to strings (char[]s). I keep getting the error that I can't use %s because in the function call I declare the parameter as a char. However if I use %c I only print the first three characters of 'H' 'e' 'l' and then I get a segmentation fault.

Error Code:
    format specifies type 'char *' but the argument has type 'char' [-Wformat]
                            printf("%s ", in[i][j]);
                                    ~~    ^~~~~~~~
                                    %c

Suggestions?

void printArray(char *in[]){
int i;
int j;
for (i = 0; i < 3; i  ){
    for (j = 0; j < 3; j  ){
        printf("%c ", in[i][j]);
    }
}


 main(){
        char *arr1[3][3];
        arr1[0][0] ="Hello";
        arr1[0][1] = "World";
        arr1[0][2] = "Today";
        arr1[1][0] = "Is";
        arr1[1][1] = "September";
        arr1[1][2] = "28";
        arr1[2][0] = "th";
        arr1[2][1] = "2021";
        arr1[2][2] = "yay";
        char *j = arr1[0][0];
        int k; 
        int p;
        printf("Before: \n");
        printArray(&j);

To reiterate, the goal is send the array of strings and then print them in the function "printArray"

Sorry if this is an easy question, again very new to C

Thank you

CodePudding user response:

Use variable length arrays (VLAs). They were added to C exactly for this purpose:

void printArray(int n, int m, char *in[n][m]){
  for (int i = 0; i < n; i  ){
    for (int j = 0; j < m; j  ){
        printf("%s ", in[i][j]);
    }
  }
}


int main() {
  char *arr1[3][3];
  ... initialize arr1
  printArray(3, 3, arr1);
}

EDIT

As stated in the comment the size expression in [n] could be omitted as it is ignored by the compiler. Though it is still useful for self-documenting. The alternative declaration could be:

void printArray(int n, int m, char *in[static n][m])

The keyword static instructs the compiler that at least first n elements of pointed by in are valid.

CodePudding user response:

change
printArray(char *in[])
to
printArray(const char * in[][3])

and
printArray(&j)
to
printArray(arr1)

Then, you should be able to use %s.

You're passing a 1D array and wanting to use it as 2D in printing.

  •  Tags:  
  • c
  • Related