1

我正在关注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;
  }
4

4 回答 4

10

此行需要演员表:

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

应该:

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

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

于 2012-07-13T17:47:25.377 回答
4

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

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

如果您希望编译器将其编译为 C,您要么需要更改其文件扩展名,要么将开关/TC传递给编译器以告诉它将文件编译为 C。

于 2012-07-13T17:48:48.413 回答
3
struct Person *who = malloc(sizeof(struct Person)); 

这需要在 C++ 中进行转换:

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

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

于 2012-07-13T17:47:37.353 回答
0

错误消息是由于 C 不需要显式转换,而 C++ 需要。尝试确保编译器将源代码视为 C 而不是 C++。

于 2012-07-13T17:50:36.243 回答