簡體   English   中英

將指向字符串的指針數組傳遞給函數

[英]Passing an array of pointers to strings into a function

我試圖將一個指向字符串(名稱)的指針數組傳遞給一個函數(foo)並從中讀取。 以下代碼產生分段錯誤。 有人可以幫我弄清楚為什么這段代碼會導致分段錯誤嗎? 我希望能夠通過函數傳遞數組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);

問題是foo的參數類型以及調用它的方式。 foo的參數類型char* []name不兼容。 我在帶有-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[]) {

foo更改為:

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

一切都會好起來的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM