You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Create an Array of struct Using the malloc() Function in C
There is another way to make an array of struct in C. The memory can be allocated using the malloc() function for an array of struct. This is called dynamic memory allocation.
The malloc() (memory allocation) function is used to dynamically allocate a single block of memory with the specified size. This function returns a pointer of type void.
The returned pointer can be cast into a pointer of any form. It initializes each block with the default garbage value.
The syntax of malloc() function is as below:
ptrVariable = (cast-type*) malloc(byte-size)
The complete program to create an array of struct dynamically is as below.
#include<stdio.h>
int main(int argc, char** argv)
{
typedef struct
{
char* firstName;
char* lastName;
int rollNumber;
} STUDENT;
int numStudents=2;
int x;
STUDENT* students = malloc(numStudents * sizeof *students);
for (x = 0; x < numStudents; x++)
{
students[x].firstName=(char*)malloc(sizeof(char*));
printf("Enter first name :");
scanf("%s",students[x].firstName);
students[x].lastName=(char*)malloc(sizeof(char*));
printf("Enter last name :");
scanf("%s",students[x].lastName);
printf("Enter roll number :");
scanf("%d",&students[x].rollNumber);
}
for (x = 0; x < numStudents; x++)
printf("First Name: %s, Last Name: %s, Roll number: %d\n",students[x].firstName,students[x].lastName,students[x].rollNumber);
return (0);
}
Output:
Enter first name:John
Enter last name: Williams
Enter roll number:1
Enter first name:Jenny
Enter last name: Thomas
Enter roll number:2
First Name: John Last Name: Williams Roll Number:1
First Name: Jenny Last Name: Thomas Roll Number:2
The text was updated successfully, but these errors were encountered:
Create an Array of struct Using the malloc() Function in C
There is another way to make an array of struct in C. The memory can be allocated using the malloc() function for an array of struct. This is called dynamic memory allocation.
The malloc() (memory allocation) function is used to dynamically allocate a single block of memory with the specified size. This function returns a pointer of type void.
The returned pointer can be cast into a pointer of any form. It initializes each block with the default garbage value.
The syntax of malloc() function is as below:
ptrVariable = (cast-type*) malloc(byte-size)
The complete program to create an array of struct dynamically is as below.
Output:
Enter first name:John
Enter last name: Williams
Enter roll number:1
Enter first name:Jenny
Enter last name: Thomas
Enter roll number:2
First Name: John Last Name: Williams Roll Number:1
First Name: Jenny Last Name: Thomas Roll Number:2
The text was updated successfully, but these errors were encountered: