2012-07-13 60 views
1

我在學習C的艱難之路,當我嘗試運行此程序時,出現以下錯誤消息:從'void *'到指向非'空'的轉換需要一個明確的強制轉換(第17行)

從'void *'轉換爲指向非'空'的指針需要顯式強制轉換。

我不知道如何解決這個問題,我必須改變結構中的返回變量?

不管怎麼說,這裏的代碼:(在Visual C++ 2010上編譯,還沒有嘗試過GCC)。

//learn c the hardway 

    #include <assert.h> 
    #include <stdlib.h> 
    #include <string.h> 
    #include <stdio.h> 

    struct Person { 
     char *name; 
     int age; 
     int height; 
     int weight; 
    }; 

    struct Person *Person_create(char *name, int age, int height, int weight) 
    { 
     struct Person *who = malloc(sizeof(struct Person)); 
     assert(who != NULL); 

     who->name = strdup(name); 
     who->age = age; 
     who->height = height; 
     who->weight = weight; 

     return who; 
    } 

    void Person_destroy(struct Person *who) 
    { 
     assert(who != NULL); 

     free(who->name); 
     free(who); 
    } 

    void Person_print(struct Person *who) 
    { 
     printf("Name: %s\n", who->name); 
     printf("\tAge: %d\n", who->age); 
     printf("\tHeight: %d\n", who->height); 
     printf("\tWeight: %d\n", who->weight); 
    } 

    int main(int argc, char *argv[]) 
    { 
     // make two people structures 
     struct Person *joe = Person_create(
       "Joe Alex", 32, 64, 140); 

     struct Person *frank = Person_create(
       "Frank Blank", 20, 72, 180); 

     // print them out and where they are in memory 
     printf("Joe is at memory location %p:\n", joe); 
     Person_print(joe); 

     printf("Frank is at memory location %p:\n", frank); 
     Person_print(frank); 

     // make everyone age 20 years and print them again 
     joe->age += 20; 
     joe->height -= 2; 
     joe->weight += 40; 
     Person_print(joe); 

     frank->age += 20; 
     frank->weight += 20; 
     Person_print(frank); 

     // destroy them both so we clean up 
     Person_destroy(joe); 
     Person_destroy(frank); 

     return 0; 
    } 
+3

如果你爲C編譯,它應該可以工作。但在C++中,投射是必要的。 (如果你選擇C++,你可能會考慮使用更多類似於C++的特性。) – Mysticial 2012-07-13 17:47:46

+0

你是將它編譯爲C還是C++?語言不一樣。 – 2012-07-13 17:47:46

+0

通過錯誤消息學習?這確實是「困難的方式」。我相信有更好的方法。 – 2012-07-13 17:51:26

回答

8

這條線需要投:

struct Person *who = malloc(sizeof(struct Person)); 

應該是:

struct Person *who = (struct Person *)malloc(sizeof(struct Person)); 

這僅僅是因爲你正在編譯此代碼爲C++而不是C.在C,演員是不需要的,併爲你隱式完成。

+0

謝謝!我只是認爲MS C++會爲C編譯,因爲我使用了c頭文件。 – TheBlueCat 2012-07-13 18:14:38

3
struct Person *who = malloc(sizeof(struct Person)); 

這需要在C++待澆鑄:

struct Person *who = (struct Person *) malloc(sizeof(struct Person)); 

在C,因爲存在從void *任何對象指針類型的隱式轉換的轉換是不必要的。這種隱式轉換在C++中不存在,因此在C++中需要強制轉換。

4

Visual C++編譯器將嘗試從正在編譯的源文件的文件擴展名中確定正在編譯的語言。例如,擴展名爲.cpp的文件編譯爲C++,擴展名爲.c的文件編譯爲C.

您的程序似乎是有效的C,但無效C++:在C中,void*T*轉換是隱含的;在C++中需要強制轉換。

如果你希望編譯器編譯爲C,你要麼需要改變它的文件擴展名,或通過the /TC switch編譯器來告訴它來編譯文件爲C.

+0

再一次,謝謝! – TheBlueCat 2012-07-13 18:14:49

0

該錯誤消息是由引起事實上C並不需要明確地進行這種轉換,而C++則需要這樣的轉換。嘗試確保編譯器將源視爲C而不是C++。