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 a struct in C

1 Answer

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

struct worker 
{
    char name[32];
    int age;
    float salary;
};

int main(int argc, char **argv) 
{ 
    struct worker *w;
    
    w = (struct worker *)malloc(sizeof(struct worker));
    if (w == NULL)
    {
        puts("Allocation Error (malloc)");
        exit(1);
    }
        
    strcpy(w->name, "Jennifer");
    w->age = 45;
    w->salary = 23789;

    printf("Worker Details:\n");
    printf("name: %s - age: %d - salary: %.2f\n", w->name, w->age, w->salary);
    
    free(w);
    
    return 0;
}

/*
run:

Type a string up to 127 characters: have fun
Worker Details:
name: Jennifer - age: 45 - salary: 23789.00

*/

 



answered Jul 10, 2015 by avibootz

Related questions

1 answer 132 views
132 views asked May 4, 2021 by avibootz
1 answer 189 views
2 answers 258 views
1 answer 173 views
1 answer 180 views
1 answer 176 views
176 views asked Jul 11, 2019 by avibootz
...