无效转换为’void *’到’node *’
我有一个产生错误的C程序:
invalid conversion from 'void*' to 'node*' [-fpermissive]
这是我的代码:
#include #include #include struct node { int data; struct node* next; }; struct node* onetwothree(); int main() { struct node* ptr; ptr = onetwothree(); return 0; } struct node* onetwothree() { struct node* head; struct node* temp; head = malloc(sizeof(struct node)); temp = head; for(int i=1; idata = i; if(inext; else temp->next = NULL; } return head; }
我究竟做错了什么?
在C中, void*
可隐含地转换为T*
,其中T
是任何类型。 从第6.3.2.3节C99标准的指针 :
指向void的指针可以转换为指向任何不完整或对象类型的指针。 指向任何不完整或对象类型的指针可能会转换为指向void的指针并再次返回; 结果应该等于原始指针。
malloc()
返回一个void*
并且可以在不转换为head
情况下赋值,即struct node*
。 在C ++中不是这样,所以我怀疑正在使用C ++编译器来编译这个C代码。
例如:
#include int main() { int* i = malloc(sizeof(*i)); return 0; }
编译时:
gcc -Wall -Werror -pedantic -std = c99 -pthread main.c -o main
没有错误。 编译时:
g ++ -Wall -Werror -pedantic -std = c ++ 11 -pthread main.cpp -o main
发出:
main.cpp:在函数’int main()’中:main.cpp:5:31:错误:从’void *’到’int *’的无效转换[-fpermissive]
另外, onetwothree()
函数没有正确分配内存。 它仅分配一个struct node
:
head = malloc(sizeof(struct node));
然后,最终,取消引用head->next->next
,这是未定义的行为。 每个struct node
都需要单独的malloc()
。 记得free()
什么是malloc()
d。
您遇到此警告/错误,因为您正在使用malloc
(返回void*
)初始化node*
类型的结构而不进行显式转换。
要摆脱此错误,您可以通过以下方式更改代码:
head = (struct node *)malloc(sizeof(struct node));
或者您也可以在编译器中添加“-fpermissive”标志,然后忽略这些错误。
编辑:但是,我没有想到这不应该在C编译器中发生这一事实