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

...