所以我确定这个问题已经回答了很多次,但我不知道如何解决我的情况。我截取了我的程序片段,其中包含我的警告生成代码:
#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 文本.c text.c:在函数“main”中: text.c:18:5: 警告:从不兼容的指针类型传递‘inputData’的参数 2 [默认启用] 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
}
最佳答案
数组名称在传递给函数时转换为指向其第一个元素的指针。 name
将被转换为 &name[0]
(指向 char
类型的指针)这是第一个元素的地址数组名称
。因此,函数的第二个参数必须是指向char
类型的指针。
char *storage[size]
在声明为函数参数时等同于 char **storage
。因此,将 char *storage[size]
更改为 char *storage
。
关于c - 将指针传递给字符串,不兼容的指针类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25768008/