从'无效*'到'节点*'无效的转换[-fpermissive] [英] invalid conversion from 'void*' to 'node*' [-fpermissive]

查看:856
本文介绍了从'无效*'到'节点*'无效的转换[-fpermissive]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个产生错误的C程序:

I have a C program that produces an error:

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

下面是我的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?

推荐答案

在C,一个无效* 是含蓄转化为 T * ,其中 T 是任何类型的。从部分的 6.3.2.3指针的C99标准:

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:

要作废的指针可以转换或从一个指向任何不完全或对象
  类型。一个指向任何完整或对象类型可被转换成一指向void
  并再次返回;结果应比较等于原始指针

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()返回无效* 是分配,但不强制转换为,一个结构节点* 。这不是C ++真的,所以我怀疑C ++编译器被用于编译此C code。

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.

例如:

#include <stdlib.h>

int main()
{
    int* i = malloc(sizeof(*i));
    return 0;
}

当编译:

GCC -Wall -pedantic -Werror -std = C99 -pthread的main.c -o主

gcc -Wall -Werror -pedantic -std=c99 -pthread main.c -o main

发射没有错误。当编译:

emits no errors. When compiled with:

G ++ -Wall -pedantic -Werror -std = C ++ 11 -pthread的main.cpp -o主

g++ -Wall -Werror -pedantic -std=c++11 -pthread main.cpp -o main

发出:

main.cpp中:在函数'廉政的main():
  main.cpp中:5:31:错误:从无效转换'​​无效*'到'INT *'[-fpermissive]

main.cpp: In function 'int main()': main.cpp:5:31: error: invalid conversion from 'void*' to 'int*' [-fpermissive]

此外,在 onetwothree()函数没有被正确分配内存。它分配一个结构节点


Additionally, the onetwothree() function is not allocating memory correctly. It allocates one struct node only:

head = malloc(sizeof(struct node));

然后,最终废除的流浆&GT;下一步 - &gt;接下来这是不确定的行为。一个单独的的malloc()需要每结构节点
记住免费()什么的malloc() D。

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.

这篇关于从'无效*'到'节点*'无效的转换[-fpermissive]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆