因此,我正在关注 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 类型的值不能分配给“node *”类型的实体,因此我将 (node *) 强制转换为每个包含 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 新手)试图解决这个问题半小时之后,我无法想出解决方案。我该如何解决这个错误?我开始认为这是一个编译器问题,但如果不是必需的,我不想更改编译器。