从'void *'转换为指向非'void'的指针需要显式转换(第17行)

时间:2012-07-13 17:45:46

标签: c++ c visual-studio-2010 visual-c++

我正在阅读“学习艰难的方式”一书,当我尝试运行此程序时,我收到此错误消息:

  

从'void *'转换为指向非'''的指针需要显式转换。

我不知道如何解决这个问题,我是否必须更改struct中的return变量?

无论如何,请看一下代码:(在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;
  }

4 个答案:

答案 0 :(得分:9)

此行需要演员:

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

应该是:

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

这只是因为您将此代码编译为C ++而不是C.在C中,不需要强制转换,并且隐式为您完成。

答案 1 :(得分:4)

Visual C ++编译器将尝试从正在编译的源文件的文件扩展名中确定正在编译的语言。例如,扩展名为.cpp的文件编译为C ++,扩展名为.c的文件编译为C.

您的程序似乎是有效的C,但不是有效的C ++:在C中,void*T*转换是隐含的;在C ++中需要强制转换。

如果您希望编译器将其编译为C,您需要更改其文件扩展名,或者将the /TC switch传递给编译器,告诉它将文件编译为C.

答案 2 :(得分:3)

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

这需要用C ++表示:

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

在C中,不需要强制转换,因为存在从void *到任何对象指针类型的隐式转换。这种隐式转换在C ++中不存在,因此在C ++中需要强制转换。

答案 3 :(得分:0)

错误消息是由于C不显式地需要这样的转换,而C ++确实如此。尝试确保编译器将源视为C而不是C ++。