Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c - invalid conversion from 'void*' to 'node*' [-fpermissive]

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...