c - 为结构体分配内存时出现 Malloc 错误

标签 c dev-c++

#include<stdio.h>
#include<conio.h>
struct Node{
    int number;
    struct Node * next;
};

struct Node * insertNodeInLinkedList(int number,struct Node * startOfList){
    if(startOfList == NULL){
        startOfList = (struct Node *)malloc(sizeof(struct Node));
        startOfList->number = number;
        startOfList->next = NULL;
    }else{
        struct Node * temporaryNode = startOfList;
        struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
        while(temporaryNode->next != NULL){
            temporaryNode = temporaryNode->next;
        }

        newNode->number = number;
        newNode->next = NULL;
        temporaryNode->next = newNode;

    }
    return startOfList;
}

void display(struct Node * startOfList){
    struct Node * temporaryNode = startOfList;
    while(temporaryNode != NULL){
        printf("%d",temporaryNode->number);
        temporaryNode = temporaryNode->next;
    }   
}

int main (void){
    int howManyNodes = 0;
    int counter = 0;
    int enteredNumber = 0;
    struct Node * startOfMyList = NULL;

    printf("How many nodes do you want in your linked list?");
    scanf("%d",&howManyNodes);

    while(counter < howManyNodes){
        printf("Enter number: ");
        scanf("%d",&enteredNumber);
        startOfMyList = insertNodeIntoLinkedList(enteredNumber,startOfMyList);
        counter++;
    }
    display(startOfMyList);
    getch();
    return 0;
}  

这是我插入和显示链表节点的简单程序。然而,这一行:

startOfList = (struct Node *)malloc(sizeof(struct Node));  

被标记为错误。我不知道为什么。

这里出了什么问题?

最佳答案

您的malloc看来是正确的。

对于您的新错误,这只是因为 main您正在调用insertNodeIntoLinkedList并且您之前定义了该函数:

insertNodeInLinkedList
//        ^^

此外,您还需要包含<stdlib.h>对于 malloc 功能。

关于c - 为结构体分配内存时出现 Malloc 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18799820/

相关文章:

python - SOL_有什么用?

c - x64 上是否需要 int ?

c++ - 有什么方法可以增加一个字符吗?

c++ - 如何从 C++ 调用 perl?

c++ - 函数原型(prototype)中的参数名称

c++ - Orwell Dev C++ 不适用于 C++11

c - 如何为我的 char 指针分配内存?

c - malloc 分配的内存是否超出了我的要求?

c++ - 无法识别的命令行选项 -std=c++11 或 -std=c++0x

C编程数组有帮助吗?