从'void *'到指向非'void'的转换需要一个显式转换(第17行) [英] Conversion from 'void*' to pointer to non-'void' requires an explicit cast (Line 17)
本文介绍了从'void *'到指向非'void'的转换需要一个显式转换(第17行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我跟着这本书学习困难的方式,当我尝试运行这个程序,我得到这个错误消息:
I'm following the book Learn C the Hard Way and when I try to run this program I get this error message:
从void *转换为非void的指针需要显式转换。
Conversion from 'void*' to pointer to non-'void' requires an explicit cast.
我不知道如何解决这个,我必须改变结构中的返回变量?
I'm not sure how to resolve this, do I have to change the return variable in the struct?
看看反正,这里的代码:(在Visual C ++ 2010上编译,没有尝试过GCC
Take a look anyway, here the code: (Compiling on Visual C++ 2010, haven't tried GCC yet).
//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;
}
推荐答案
struct Person *who = malloc(sizeof(struct Person));
应为:
struct Person *who = (struct Person *)malloc(sizeof(struct Person));
这是因为你正在编译这段代码为C ++,而不是C。强制转换是不需要的,并为您隐性完成。
This is only because you're compiling this code as C++, and not C. In C, the cast is unneeded, and implicitly done for you.
这篇关于从'void *'到指向非'void'的转换需要一个显式转换(第17行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文