2013-05-28 52 views
6

我有一個產生錯誤的C程序:從無效轉換 '無效*' 到 '節點*'[-fpermissive]

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

這裏是我的代碼:

#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; 
} 

我是什麼做錯了?

+2

你如何確保你正在編譯此爲C代碼,而不是C++代碼嗎? – nos

+1

@Sildoreth請**不要**編輯帖子以改變編碼風格以適應您自己的主觀偏好。這只是破壞行爲,並不會幫助任何人。您的編輯應該永遠不會被批准。編輯回滾。 – Lundin

+0

這就是說,這篇文章的縮寫是非常不一致的,需要修復。只需更改縮進即可進行編輯。 – Lundin

回答

15

在C中,void*可隱式轉換爲T*,其中T是任何類型。從部分C99標準6.3.2.3指針

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()返回void*並分配,但不強制轉換爲head,一個struct node*。在C++中這不是真的,所以我懷疑正在使用C++編譯器來編譯這個C代碼。

例如:

#include <stdlib.h> 

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: In function 'int main()': main.cpp:5:31: error: invalid conversion from 'void*' to 'int*' [-fpermissive]


另外,onetwothree()功能沒有被正確分配存儲器。它分配只有一個struct node

head = malloc(sizeof(struct node)); 

然後,最終取消引用head->next->next這是不確定的行爲。每個struct node都需要個人malloc()。 記得free()什麼是malloc() d。

+0

我不記得細節,但認爲指向函數和數據的指針在c中不可互換?那是錯的嗎?它應該是「任何數據類型」? –

+0

@andrewcooke沒錯。然而,在我們常見的服務器/桌面平臺上,它們和posix似乎至少隱含地要求void *和函數指針是可互換的。 – nos

+0

@andrewcooke,我會用C99標準中的相關部分更新答案,C99標準指出_any不完整或對象類型_。 – hmjd

2

由於您正在使用malloc(它返回void*)來初始化node*類型的結構而不進行顯式強制轉換,因此您有此警告/錯誤。

爲了擺脫這種錯誤的,你可以這樣更改代碼:

head = (struct node *)malloc(sizeof(struct node)); 

或者你還可添加「-fpermissive」標誌,以你的編譯器,然後將忽略這些錯誤。

編輯:但是,是的,我沒有想到的是,這不應該在C編譯器發生反正

+4

-1,錯誤的答案。這是C而不是C++,在C中'void *'很容易轉換爲任何指向數據類型的指針。 –

+0

是的,我編輯了我的答案,沒有想到它,對不起。 –

+0

@JensGustedt如果使用C++ comilper進行編譯,那麼即使C代碼也會顯示此錯誤,因此它不是一個錯誤的答案,並且不值得讚賞。 – A4L

相關問題