2014-09-10 132 views
4

所以我相信這個問題已經回答了很多次,但是我無法看到如何解決我的情況。我把我的節目的片段,包含我的警告生成代碼:傳遞指向字符串的指針,不兼容的指針類型

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

inputData(int size, char *storage[size]) 
{ 
    int iterator = -1; 

    do { 
     iterator++; 
     *storage[iterator] = getchar(); 
    } while (*storage[iterator] != '\n' && iterator < size); 
} 

main() 
{ 
    char name[30]; 

    inputData(30, name); 
} 

警告消息:

$ GCC的text.c 的text.c:在函數 '主': 的text.c :18:5:warning:從不兼容的指針類型[默認啓用]傳遞'inputData'的參數2 inputData(30,name); ^的text.c:4:1:注:應爲 '字符**',但參數的類型的 '字符*' inputData(INT大小,字符*存儲[大小])

編輯:

好的,所以我設法使用一些語法來解決我的問題。我仍然不會;不介意聽到有人比我更瞭解情況,爲什麼這是需要的。這裏是我改變的:

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

inputData(int size, char *storage) // changed to point to the string itself 
{ 
    int iterator = -1; 

    do { 
     iterator++; 
     storage[iterator] = getchar(); // changed from pointer to string 
    } while (storage[iterator] != '\n'); // same as above 
} 

main() 
{ 
    char name[30]; 

    inputData(30, name); 

    printf("%s", name); // added for verification 
} 
+0

裏面'inputData()',代碼應該有3種原因而停止:1)'的getchar()''返回'\ n'' 2)'的getchar ()'返回'EOF' 3)沒有更多空間。 – chux 2014-09-10 19:14:35

回答

1

當傳遞給一個函數時,數組名被轉換爲指向其第一個元素的指針。 name將被轉換爲&name[0]指向char類型),它是數組name的第一個元素的地址。因此,你的函數的第二個參數必須是,指向char類型。

char *storage[size]當聲明爲函數參數時相當於char **storage。因此,將char *storage[size]更改爲char *storage

0

當你傳遞一個數組的功能,你可以做到這一點在兩個方面:
考慮下面的程序: -

int main() 
{ 
    int array[10]; 
    function_call(array); // an array is always passed by reference, i.e. a pointer 
    //code    // to base address of the array is passed. 
    return 0; 
} 

方法1:

void function_call(int array[]) 
{ 
    //code 
} 

方法2:

void function_call(int *array) 
{ 
    //code 
} 

兩種方法的唯一區別是語法,otherw兩者是相同的。
值得一提的是,在C語言中,數組不是按值傳遞,而是由
引用。
您可能會發現下面的鏈接有用: -

http://stackoverflow.com/questions/4774456/pass-an-array-to-a-function-by-value