Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

malloc memory for an array of structure in c #30

Open
davideuler opened this issue Sep 21, 2022 · 0 comments
Open

malloc memory for an array of structure in c #30

davideuler opened this issue Sep 21, 2022 · 0 comments

Comments

@davideuler
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant