Malloc и структуры в C дают мне ошибки (после учебника )?

Итак, я следую учебнику по 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;
}

. Функция malloc продолжала вызывать проблемы :«значение типа void не может быть присвоено сущности типа «узел *», поэтому я привожу (узел *)к каждой строке malloc -, содержащей, т. е.:

root = malloc( sizeof(struct node) );  

и т. д. Это, казалось, решило вышеупомянутую ошибку, но затем, когда я сделал это и попытался скомпилировать, возникла новая ошибка:

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 ==========

Так что да, после того, как (как полный новичок в C )пытался понять это в течение получаса, я не смог найти решение. Как я могу решить эту ошибку? Я начинаю думать, что это проблема компилятора,но я не хочу менять компилятор, если в этом нет необходимости.

5
задан ZimZim 6 September 2014 в 11:13
поделиться