How to allocate memory for a string inside the struct in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
struct worker {
    char *name;
    int age;
};
 
int main()
{ 
    struct worker w;
     
    w.name = (char *)malloc(30 * sizeof(char));
    strcpy(w.name, "Tom");
    w.age = 45;
 
    printf("name: %s : age: %d\n", w.name, w.age);
     
    free(w.name);
     
    return 0;
}

 
/*
run:
 
name: Tom : age: 45
 
*/

 



answered Jul 11, 2019 by avibootz

Related questions

2 answers 292 views
1 answer 155 views
155 views asked May 4, 2021 by avibootz
1 answer 191 views
191 views asked Jul 10, 2015 by avibootz
2 answers 174 views
2 answers 223 views
223 views asked Jul 10, 2015 by avibootz
1 answer 199 views
...