2014-09-10 135 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