C中的结构和动态记忆

问题描述 投票:-3回答:3

我是C的初学者。 我想将每个人的信息分配给一个*arr[2]指针数组 但我收到一条错误消息

'malloc' is not declared in this scope.

我该如何解决?

#include <stdio.h>

int main()
{
    struct person {
        char *name;
        int number;
        char gender;
    };

    struct person *arr[2];

    arr[0] = (struct person *) malloc(sizeof(struct person));

    arr[0]->name = "john";
    arr[0]->number = 123;
    arr[0]->gender ='m';

    arr[1] = (struct person *) malloc(sizeof(struct person));

    arr[1]->name = "jessica";
    arr[1]->number = 456;
    arr[1]->gender ='w';

    printf("%s", arr[1]->name);

    return 0;
}
c
3个回答
0
投票

一些输入而不仅仅是一个。

主要是:man page for malloc说你需要包含头文件:stdlib.h

#include <stdlib.h>

能够为你节省很多痛苦的一个习惯是检查malloc()是否成功。您必须检查malloc()返回的值。

arr[0] = malloc(sizeof(struct person));
if(arr[0] == NULL)
{
    // Since malloc has returned NULL, requested memory is not allocated
    // Accessing it is out of question

    // Some error handling implementation
    return;
}

此外,除非我们不会突然崩溃,否则我们应该总是返还借来的东西。需要释放分配的内存。互联网上有几个关于如何解除分配动态分配内存的例子。一个好的开始是阅读内存泄漏和悬空指针等概念。

另一个建议是: 如果你查看malloc的相同(或其他)手册页,你会发现malloc返回一个void指针。所以,你不必抛出malloc()结果。有this legendary post and a legendary answer解释了为什么不投。


0
投票

您应该包含一个定义malloc()的标头。通常,这将是stdlib.h。

您可以使用cppreference.com或类似网站的在线帮助来获取此信息,以及c库的完整文档。


0
投票

要实际使用函数malloc,你应该包含#include库,它声明了malloc(), calloc(), free()函数。

© www.soinside.com 2019 - 2024. All rights reserved.