我在學習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;
}
如果你爲C編譯,它應該可以工作。但在C++中,投射是必要的。 (如果你選擇C++,你可能會考慮使用更多類似於C++的特性。) – Mysticial 2012-07-13 17:47:46
你是將它編譯爲C還是C++?語言不一樣。 – 2012-07-13 17:47:46
通過錯誤消息學習?這確實是「困難的方式」。我相信有更好的方法。 – 2012-07-13 17:51:26