Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

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

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
struct worker {
    char *name;
    int age;
};
 
int main()
{ 
    struct worker *w;
     
    w = (struct worker *)malloc(sizeof(struct worker));
    if (w == NULL) {
        puts("Malloc error");
        exit(1);
    }
         
    w->name = strdup("Jennifer");
    w->age = 45;
 
    printf("name: %s : age: %d\n", w->name, w->age);
     
    free(w->name);
	free(w);
     
    return 0;
}

 
/*
run:
 
name: Jennifer : age: 45
 
*/

 



answered Jul 11, 2019 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
struct worker {
    char *name;
    int age;
};
 
int main()
{ 
    struct worker *w;
     
    w = (struct worker *)malloc(sizeof(struct worker));
    if (w == NULL) {
        puts("Malloc error");
        exit(1);
    }
         
    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);
	free(w);
     
    return 0;
}

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

 



answered Jul 11, 2019 by avibootz

Related questions

1 answer 189 views
1 answer 132 views
132 views asked May 4, 2021 by avibootz
1 answer 161 views
161 views asked Jul 10, 2015 by avibootz
2 answers 139 views
1 answer 179 views
2 answers 192 views
192 views asked Jul 10, 2015 by avibootz
...