简体   繁体   English

如何在C函数中为结构指针分配内存

[英]How to allocate memory to a struct pointer in a function in c

I am trying to use a function to allocate memory to a struct pointer, but the program enters in a not responding stance when it reaches the line of code that does that. 我正在尝试使用一个函数来将内存分配给struct指针,但是当程序到达执行该操作的代码行时,该程序将进入无响应的状态。 I tried everything, but I can't figure it out on myself. 我尝试了一切,但我自己却无法解决。 I am new to C. This is the code: 我刚接触C。这是代码:

#include <stdio.h>
#include <stdlib.h>

struct elem
{
     struct elem *node;
    int a;
};


void aloc(struct elem **p,int a)
{
     *p=(struct elem*)malloc(sizeof(struct elem));
    (*p)->a=a;
    (*p)->node=NULL;
}
int main()
{
    typedef struct elem E;
    E *p;
    aloc(p,5);
    printf("%d",p->a);


    return 0;
}

aloc(p,5); You need to pass the address of the structure pointer. 您需要传递结构指针的地址。 you pass the struct pointer itself. 您传递结构指针本身。

Solution aloc(&p,5) 解决方案 aloc(&p,5)


Few points: Do check the return value of malloc . 几个要点: 检查的返回值malloc In case it fails you won't run into error. 万一失败,您将不会出错。 (In case it returns NULL if you try to access it - it will be Undefined behavior). (如果您尝试访问它,则返回NULL-这将是未定义的行为)。

And you are casting malloc - Don't do it. 而且您正在强制malloc 要这样做。 It leads to many problems. 它导致许多问题。

Also free the dynamically allocated after you are done working with it. 使用完动态分配后,还要释放它。

Also try to read the warning that the compiler provides. 另外,请尝试阅读编译器提供的警告。 It helps. 它有助于。 (Compile the program with all warnings enabled) (在启用所有警告的情况下编译程序)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM