简体   繁体   中英

how to use malloc or new in struct?

How to use malloc to allocate memory instead for char name[50]; I don't know these concepts am new for c .

struct student

{
    char name[50];
    int roll;
    float marks;
};

int main()

{
    int c;
    printf("no. of students\n");
    scanf("%d",&c);

    struct student *s;
    s=(struct student *) malloc (sizeof(struct student));
    int i;
    printf("\nstudents information:\n");

    for(i=0;i<c;++i)
    {
        printf("enter the name:");
        scanf("%s",s[i].name);
        printf("enter roll no:");
        scanf("%d",&s[i].roll);
        printf("enter the marks:");
        scanf("%f",&s[i].marks);
        printf("\n");
    }
        printf("\ndetails of all the student:\n");

    for(i=0;i<c;++i)
    {
        printf("the student name:%s\n",s[i].name);
        printf("the student roll no. is:%d\n",s[i].roll);
        printf("the student mark is:%.2f\n",s[i].marks);
        printf("\n");
    }
    return 0;
}

With the following statement you have only allocated memory that can occupy only one student .

s = (struct student *) malloc (sizeof(struct student));

But what you need is an array of students sized c , so you have to allocated c times the memory you have allocated now, so you can use them as s[i] :

s = (struct student *) malloc (c * sizeof(struct student));
char name[50];

Declares and allocate an array of 50 chars. If you want to allocate an array dynamically, you can use malloc :

char *name = malloc(n*sizeof(char));

Where n is the desired number of elements (50 in our example).

struct student
{
    char *name;
    int roll;
    float marks;
};


#define NAME_LENGTH 128

int i;
struct student *s = malloc(sizeof(struct student) * c);
for(i = 0; i < c; i++)
    s[i].name = malloc(NAME_LENGTH);

However, there is no reason to do so, as long as NAME_LENGTH is known at compile-time.

Don't forget to free each allocated memory block once they no longer needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM