将指向字符串的数组传递给函数

时间:2015-02-19 02:27:31

标签: c pointers

我试图将一个指向字符串(名称)的指针数组传递给一个函数(foo)并从中读取。以下代码产生分段错误。有人可以帮我弄清楚为什么这段代码会导致分段错误?我希望能够通过函数传递数组名[] []并使用数据,就像我在函数外部使用名称[] []一样。

void foo(char *bar[]) {
    printf("%s\n", bar[0]);
}

//---------------Main-------------

char args[][50] = {"quick", "brown", "10", "brown", "jumps", "5"};
int i = 0;
int numbOfPoints = (sizeof(args)/sizeof(args[0]))/3;

//array of all the locations. the number will be its ID (the number spot in the array)
//the contents will be
char names[numbOfPoints][100];

for(i = 0; i < numbOfPoints; i++) {
    char *leadNode = args[i*3];
    char *endNode = args[i*3 + 1];
    char *length = args[i*3 + 2];
    int a = stringToInt(length);

    //add name
    strcpy(names[i],leadNode);
}

//printing all the names out
for(i = 0; i < numbOfPoints; i++) {
    printf("%s\n", names[i]);
}

foo(names);

1 个答案:

答案 0 :(得分:1)

问题是foo的参数类型以及您调用它的方式。参数类型foochar* []name不兼容。我在gcc 4.8.2中使用-Wall收到以下警告。

soc.c:35:4: warning: passing argument 1 of ‘foo’ from incompatible pointer type [enabled by default]
    foo(names);
    ^
soc.c:5:6: note: expected ‘char **’ but argument is of type ‘char (*)[100]’
 void foo(char *bar[]) {

foo更改为:

void foo(char (*bar)[100]) {
    printf("%s\n", bar[0]);
}

一切都应该好。