【发布时间】:2012-07-13 17:45:45
【问题描述】:
我正在阅读《Learn C the Hard Way》一书,当我尝试运行该程序时,我收到以下错误消息:
从“void*”转换为指向非“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++ 的功能。)
-
您将其编译为 C 还是 C++?语言不一样。
-
通过错误信息学习?这确实是“艰难的道路”。我相信有更好的方法。
-
您似乎编写了一个 C 程序,然后尝试使用 C++ 编译器对其进行编译。不幸的是,在大多数情况下,这是一个荒谬的行为,就像您无法在 Java 编译器中编译您的 C 程序一样。尝试通过 C 编译器运行它,您可能会获得更好的运气。
标签: c++ c visual-studio-2010 visual-c++