传递字符串指针,不兼容的指针类型。

5

我相信这个问题已经被解答很多次了,但我还是不知道如何解决我的情况。我提取了包含警告生成代码的程序片段:

#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: 警告:从不兼容的指针类型传递参数 2 给 ‘inputData’ [默认启用] inputData(30, name); ^ 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
}

inputData() 函数内,代码应该有三个停止的原因:1)getchar() 返回了 '\n' 2)getchar() 返回了 EOF 3)没有更多的空间。 - chux - Reinstate Monica
2个回答

2
当传递一个数组名到函数中时,数组名会被转换为指向其第一个元素的指针。`name` 会被转换为 `&name[0]` (指向 `char` 类型的指针),它是数组 `name` 的第一个元素的地址。因此,你的函数的第二个参数必须是指向 `char` 类型的指针。
当作为函数参数声明时,`char *storage[size]` 等价于 `char **storage`。因此,请将 `char *storage[size]` 更改为 `char *storage`。

1
当您将数组传递给函数时,有两种方法:
考虑以下程序:
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;
} 

方法一:

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

方法2:

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

这两种方法唯一的区别在于语法,除此之外两者相同。
值得一提的是,在C语言中,数组不是按值传递而是按引用传递。
您可能会发现以下链接有用:-
https://dev59.com/f2445IYBdhLWcg3wnrki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接