How to allocate memory for struct in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct worker {
    char name[16];
    int age;
};

int main()
{
    struct worker *w;

    w = (struct worker *)malloc(sizeof(struct worker));
    if (w == NULL) {
        puts("Malloc error");
        exit(1);
    }

    strcpy(w->name, "Jennifer");
    w->age = 51;

    printf("name: %s : age: %d\n", w->name, w->age);

    free(w);

    return 0;
}



/*
run:

name: Jennifer : age: 51

*/

 



answered May 4, 2021 by avibootz

Related questions

...