将指针传递给字符串,指针类型不兼容

时间:2014-09-10 14:26:37

标签: c string pointers arguments

所以我确定这个问题已经多次回答了,但我很难看到如何解决我的情况。我拿了一个包含我的警告生成代码的程序片段:

#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:在函数'main'中: text.c:18:5:警告:从不兼容的指针类型[默认启用] inputData(30,name)传递'inputData'的参数2; ^ text.c:4:1:注意:预期'char **'但参数类型为'char *'inputData(int size,char * storage [size])

编辑:

好的,所以我设法使用一些语法并解决了我的问题。我仍然不会介意听到比我更有知识的人听到为什么需要这样做。这是我改变的:

#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
}

2 个答案:

答案 0 :(得分:1)

数组名称在传递给函数时转换为指向其第一个元素的指针。 name将转换为&name[0]指向char 类型的指针),这是数组name的第一个元素的地址。因此,函数的第二个参数必须是指向char 类型的指针。

声明为函数参数时,

char *storage[size]相当于char **storage。因此,请将char *storage[size]更改为char *storage

答案 1 :(得分: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
}

两种方法的唯一区别是语法,否则两者都是相同的 值得一提的是,在C语言中,数组不是通过值传递,而是通过
传递 参考。
您可能会发现以下链接很有用: -

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