[英]Passing an array of pointers to strings into a function
I am trying to pass an array of pointers to strings (names) into a function (foo) and read from it. 我试图将一个指向字符串(名称)的指针数组传递给一个函数(foo)并从中读取。 The below code produces a segmentation fault.
以下代码产生分段错误。 Can someone please help me figure out why this code is resulting in a segmentation fault?
有人可以帮我弄清楚为什么这段代码会导致分段错误吗? I want to be able to pass the array names[][] through a function and work with the data like I would if I were using names[][] outside the function.
我希望能够通过函数传递数组names [] []并像使用函数外使用names [] []一样处理数据。
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);
The problem is the the argument type of foo
and the way you are calling it. 问题是
foo
的参数类型以及调用它的方式。 The argument type of foo
, char* []
is not compatible with name
. foo
的参数类型char* []
与name
不兼容。 I get the following warning in gcc 4.8.2 with -Wall
. 我在带有
-Wall
gcc 4.8.2中收到以下警告。
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[]) {
Change foo
to: 将
foo
更改为:
void foo(char (*bar)[100]) {
printf("%s\n", bar[0]);
}
and all should be well. 一切都会好起来的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.