Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a 2-dimensional character array to a function

Tags:

arrays

c

I am trying to create a program to take 2-dimensional array and print each line out by its own (if you have ever took the Python course in Codecademy, it's like the battleship lesson and I'm trying to print out the board). I've done numerous google searches but two-dimensional character arrays doesn't seem to be covered very well on the internet

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const int n = 5;
void printgraph(char *graph[]) {
    printf("\nPrinting graph:\n\n");
    int i = 0;
    for(i = 0; i <= 5 - 1; i++) {   // this is only a temporary solution
        printf("i %i | %s\n", i, &graph[i]);    // error here
    }
}

    int main(int argc, char *argv[]) {
    char array[5][6];    // defining the char array here
    strcpy(array[0], "abcde");
    strcpy(array[1], "fghij");
    strcpy(array[2], "klmno");
    strcpy(array[3], "pqrst");
    strcpy(array[4], "uvwxy");
 printf("array: %s\n", array[1]);   // it prints out perfectly within the function itself
    printgraph(*array);    // error here
    return 0;
}

This is what terminal tells me

$cc -g -Wall ex3.c -o ex3
ex3.c: In function ‘printgraph’:
ex3.c:11:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘char **’ [-Wformat=]
   printf("i %i | %s\n", i, &graph[i]);
   ^
ex3.c: In function ‘main’:
ex3.c:23:2: warning: passing argument 1 of ‘printgraph’ from incompatible pointer type [enabled by default]
  printgraph(*array);
  ^
ex3.c:6:6: note: expected ‘char **’ but argument is of type ‘char *’
 void printgraph(char *graph[]) {
      ^
$./ex3
array: fghij

Printing graph:

i 0 | abcde
i 1 | hij
i 2 | o
i 3 | uvwxy
i 4 | 

As you can see, not all arrays are printed out correctly. I've tried different variations taking out pointers, but this one is the only one that works halfway decently

like image 628
Humbleness Avatar asked Dec 01 '25 02:12

Humbleness


1 Answers

Why not just pass the whole array to the function and print out the required stuff inside the function.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const int n = 5;
void printgraph(char graph[][6]) { /* ---> Changes made here */
    printf("\nPrinting graph:\n\n");
    int i = 0;
    for(i = 0; i <= 5 - 1; i++) {   
        printf("i %i | %s\n", i, graph[i]);   /* Check the changes here */
    }
}

int main(int argc, char *argv[]) {
char array[5][6];    // defining the char array here
strcpy(array[0], "abcde");
strcpy(array[1], "fghij");
strcpy(array[2], "klmno");
strcpy(array[3], "pqrst");
strcpy(array[4], "uvwxy");
printgraph(array);    /* Pass the array to the function */
return 0;
}
like image 57
Gopi Avatar answered Dec 02 '25 17:12

Gopi



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!