C中的malloc和结构体给我错误(按照教程)?

Zim*_*Zim 5 c c++ malloc struct visual-studio-2010

所以我正在学习关于C的教程,因为他们使用malloc函数而且我的编译器(Visual Studio C++ 10.0)似乎没有用得很好.所以我完全按照说明操作,我可以编译C,除了在这个特定的代码中,它给了我一个错误(代码从教程网站获取):

#include <stdio.h>
#include <stdlib.h>

struct node {
  int x;
  struct node *next;
};

int main()
{
    /* This won't change, or we would lose the list in memory */
    struct node *root;       
    /* This will point to each node as it traverses the list */
    struct node *conductor;  

    root = malloc( sizeof(struct node) );  
    root->next = 0;   
    root->x = 12;
    conductor = root; 
    if ( conductor != 0 ) {
        while ( conductor->next != 0)
        {
            conductor = conductor->next;
        }
    }
    /* Creates a node at the end of the list */
    conductor->next = malloc( sizeof(struct node) );  

    conductor = conductor->next; 

    if ( conductor == 0 )
    {
        printf( "Out of memory" );
        return 0;
    }
    /* initialize the new memory */
    conductor->next = 0;         
    conductor->x = 42;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

malloc函数一直给出麻烦:"void类型的值不能分配给类型为"node*"的实体,所以我将(node*)转换为每个包含malloc的行,即:

root = malloc( sizeof(struct node) );  
Run Code Online (Sandbox Code Playgroud)

这似乎解决了上面提到的错误但是当我这样做并尝试编译一个新的错误时出现:

1>------ Build started: Project: TutorialTest, Configuration: Debug Win32 ------
1>  TutorialTest.c
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(16): error C2065: 'node' : undeclared identifier
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(16): error C2059: syntax error : ')'
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(27): error C2065: 'node' : undeclared identifier
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(27): error C2059: syntax error : ')'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Run Code Online (Sandbox Code Playgroud)

所以是的,在(作为一个完整的C新手)尝试解决这个问题半小时之后,我无法想出解决方案.我该如何解决这个错误?我开始认为这是一个编译器问题,但如果不是必需的话,我不想改变编译器.

Mik*_*our 15

问题是您正在使用C++编译器编译C代码.C允许从void *对象指针转换; C++没有.

你说你添加了一个演员,但没有告诉我们它是什么样的.如果它看起来像这样,那么代码应该编译为C和C++:

root = (struct node *) malloc(sizeof (struct node));
Run Code Online (Sandbox Code Playgroud)

或者,可能有一种方法可以告诉编译器将其视为C,但我不太了解该编译器可以帮助您.