我正在尝试创建一个程序,以获取二维数组并将每一行单独打印出来(如果您曾经参加过Codecademy的Python课程,就像战舰游戏中的课程,我正在尝试打印出游戏板)。我已经进行了多次谷歌搜索,但是似乎互联网上没有很好地介绍二维字符数组。
#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;
}
这是终端告诉我的信息
$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 |
正如您所看到的,不是所有的数组都能正确地打印出来。我尝试了不同的变化,去掉指针,但这个方法是唯一一个表现相对较好的。
printf
中使用graph[i]
而不是&graph[i]
。 - Himanshu