Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to pass an array of 2D strings to a function and print it

Tags:

c

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


1 Answers

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.

like image 64
kalyanswaroop Avatar answered Dec 21 '25 05:12

kalyanswaroop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!