简体   繁体   中英

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. I tried everything, but I can't figure it out on myself. I am new to C. This is the code:

#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)


Few points: Do check the return value of 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).

And you are casting malloc - Don't do it. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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