I have a C program that produces an error:
invalid conversion from 'void*' to 'node*' [-fpermissive]
Here's my code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
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; i<=3; i++)
{
temp->data = i;
if(i<3)
temp=temp->next;
else
temp->next = NULL;
}
return head;
}
What am I doing wrong?
In C, a void* is implicity convertible to a T* where T is any type. From section 6.3.2.3 Pointers of the C99 standard:
A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
malloc() returns a void* and is assignable without casting to head, a struct node*. This is not true in C++, so I suspect a C++ compiler is being used to compile this C code.
For example:
#include <stdlib.h>
int main()
{
int* i = malloc(sizeof(*i));
return 0;
}
when compiled with:
gcc -Wall -Werror -pedantic -std=c99 -pthread main.c -o main
emits no errors. When compiled with:
g++ -Wall -Werror -pedantic -std=c++11 -pthread main.cpp -o main
emits:
main.cpp: In function 'int main()': main.cpp:5:31: error: invalid conversion from 'void*' to 'int*' [-fpermissive]
Additionally, the onetwothree() function is not allocating memory correctly. It allocates one struct node only:
head = malloc(sizeof(struct node));
and then, eventually, dereferences head->next->next which is undefined behaviour. An individual malloc() is required for every struct node.
Remember to free() what was malloc()d.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With