为什么我从不兼容的指针类型警告中得到初始化?
Why am I getting an initialization from incompatible pointer type warning?
所以我在 Linux 上使用 gcc 并且在单独的文件中有以下两个代码片段(仅包含相关的代码部分):
int main()
{
/* Code removed */
int_pair_list *decomp = prime_decomp(N);
if (decomp)
while(decomp->next)
decomp = decomp->next;
printf("%d\n" decomp->value_0);
}
int_pair_list *prime_decomp(unsigned int n)
{
int_pair_list *head = malloc(sizeof(*head));
int_pair_list *current;
/* method body removed, current and head remain as int_pair_list pointers */
return current ? head : NULL;
}
程序编译和运行正确,但在编译期间,我收到警告:
problem_003.c: In function ‘main’:
problem_003.c:7:26: warning: initialization from incompatible pointer type [enabled by default]
int_pair_list *decomp = prime_decomp(N);
^
我是 C 的新手,我无法理解为什么会收到此警告。
在 C 中,函数(或其原型)应该在声明之前使用它以确定它的正确签名。否则编译器将尝试 "guess" 正确的签名。虽然它可以从调用中推断出参数类型,但 return 值类型并非如此,默认为 int
。在你的代码中,函数在使用之前没有原型,所以编译器假设它是 returning int
。这就是它警告您类型分配不兼容的原因。
所以我在 Linux 上使用 gcc 并且在单独的文件中有以下两个代码片段(仅包含相关的代码部分):
int main()
{
/* Code removed */
int_pair_list *decomp = prime_decomp(N);
if (decomp)
while(decomp->next)
decomp = decomp->next;
printf("%d\n" decomp->value_0);
}
int_pair_list *prime_decomp(unsigned int n)
{
int_pair_list *head = malloc(sizeof(*head));
int_pair_list *current;
/* method body removed, current and head remain as int_pair_list pointers */
return current ? head : NULL;
}
程序编译和运行正确,但在编译期间,我收到警告:
problem_003.c: In function ‘main’:
problem_003.c:7:26: warning: initialization from incompatible pointer type [enabled by default]
int_pair_list *decomp = prime_decomp(N);
^
我是 C 的新手,我无法理解为什么会收到此警告。
在 C 中,函数(或其原型)应该在声明之前使用它以确定它的正确签名。否则编译器将尝试 "guess" 正确的签名。虽然它可以从调用中推断出参数类型,但 return 值类型并非如此,默认为 int
。在你的代码中,函数在使用之前没有原型,所以编译器假设它是 returning int
。这就是它警告您类型分配不兼容的原因。