Ask Your Question
4

How can space be allocated for a struct using malloc?

asked 2023-06-18 09:25:55 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-18 09:54:01 +0000

devzero gravatar image

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);
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-18 09:25:55 +0000

Seen: 10 times

Last updated: Jun 18 '23