Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To allocate space for a struct using malloc, follow these steps:

  1. Define your struct and its members. For example:
typedef struct {
    int id;
    char name[20];
    float salary;
} Employee;
  1. Call malloc and pass in the size of the struct:
Employee *emp = (Employee *)malloc(sizeof(Employee));
  1. Check if the memory allocation was successful:
if (emp == NULL) {
    printf("Memory allocation failed");
    exit(1);
}
  1. Access the struct members and assign values:
emp->id = 1001;
strcpy(emp->name, "John");
emp->salary = 50000.00;
  1. When done using the struct, free the allocated memory:
free(emp);