c++ - C 中的 Malloc 和结构给我错误(遵循教程)?

标签 c++ c visual-studio-2010 struct malloc

因此,我正在学习有关 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 新手)尝试解决这个问题半小时后,我想不出解决方案。我该如何解决这个错误?我开始认为这是一个编译器问题,但如果不是必需的话,我不想更改编译器。

最佳答案

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

你说你添加了类型转换,但没有向我们展示它的样子。如果看起来像这样,那么代码应该同时编译为 C 和 C++:

root = (struct node *) malloc(sizeof (struct node));

或者,可能有一种方法可以告诉编译器将其视为 C,但我对该编译器的了解还不够多,无法在这方面为您提供帮助。

关于c++ - C 中的 Malloc 和结构给我错误(遵循教程)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11037987/

相关文章:

C++ 静态成员函数与 lambda 开销

c++ - 检查字符串是否是正则表达式的潜在匹配项

c - oclMat 对齐实际上是什么意思?

c - 如何找到给定 GArray 的长度?

visual-studio-2010 - 什么是允许根据每个客户轻松定制产品的良好解决方案结构?

c++ - 如何将指针的关系比较变成错误?

c++ - 可视化图像数据的调试器

c - Linux 中的 DMA 如何处理 memcpy

visual-studio-2010 - Microsoft Visual Studio 2010 Service Pack 1 安装

c# - 访问 Visual Studio 扩展中的当前代码 Pane