Home > Net >  how to use gets() function in dynamic memory allocation with structure in c
how to use gets() function in dynamic memory allocation with structure in c

Time:05-21

#include <stdio.h>
#include <stdlib.h>

struct data
{
    char name[100];
    int age;
};

int main()
{
    struct data *p;
    int i, n;
    printf("\nENTER THE SIZE OF STRUCTURE:");
    scanf("%d", &n);
    p = (struct data *)calloc(n, sizeof(struct data));

    if (n < 0 || p == NULL)
    {
        printf("\nSTUCTURE DOESNOT CREATED");
    }
    else
    {
        for (i = 0; i < n; i  )
        {
            printf("\nENTER THE INFO FOR %d STRUCTER", i   1);
            printf("\nENTER THE NAME:");
            gets((p   i)->name);

            printf("\nENTER THE AGE:");
            scanf("%d", &(p   i)->age);
        }
        for (i = 0; i < n; i  )
        {
            printf("\n");
            printf("\n%d\t\t%s\t\t%d", i   1, (p   i)->name, (p   i)->age);
        }
        free(p);
    }
}

can I use gets() function to store string in this above code I know I can store with scanf() but it will terminated after white spaces and the reference of this program https://www.programiz.com/c-programming/examples/structure-dynamic-memory-allocation

CodePudding user response:

how to use gets() function?

Do not use gets() for anything. This function is obsolete and cannot be used safely. Instead of gets((p i)->name), you can write:

scanf("            
  • Related