简体   繁体   中英

Simple structure with dynamic memory allocation

Right after scanning the second element, the program crashes. It is not able to go to the scanning of the third element(ie grade). Need help, in figuring out what I am wrong wrong.

#include<stdio.h>
#include<stdlib.h>
#define NUM 2
typedef struct STUDENT
{
    int ID;
    char *name;
    char *grade;
};
int main ()
{
        int i;
    struct STUDENT *s;
    s = (struct STUDENT*)malloc(NUM*sizeof(struct STUDENT*));
    printf("Enter Student's ID, Name and Grade:\n");
    for(i=0;i<NUM;i++)
    {
        printf("Enter ID:\n");
        scanf("%d", &(s+i)->ID);
        printf("Enter Student Name:\n");
        scanf("%s", (s+i)->name);
        printf("Enter Grade:\n");
        scanf("%s", (s+i)->grade);
        printf("\n");
    }
    printf("\nInformation of the student's are:\n");
    for(i=0;i<NUM;i++)
    {
        printf("Student ID = %d\n", (s+i)->ID);
        printf("Student Name = %s\n", &(s+i)->name);
        printf("Student grade = %c\n", &(s+i)->grade);
        printf("\n");
    }
    return 0;
}
malloc(NUM*sizeof(struct STUDENT*));

should be

malloc(NUM*sizeof(struct STUDENT));

also, the name and grade are not buffers but pointers. You may need a buffer (char array) or allocate memory for it dynamically.

You do not allocate memory for grade and name in struct STUDENT . Trying to read input and write it to them produces undefined behavior.

Add the necessary malloc s, for example with a given maximum length STR_MAX :

s[i].name = malloc(STR_MAX);
s[i].grade = malloc(STR_MAX);

See the other answers for further errors.

  1. struct STUDENT *s; should be declared like this:

     STUDENT *s; 
  2. No need to cast void * from malloc . Change this line s = (struct STUDENT*)malloc(NUM*sizeof(struct STUDENT*)); to this:

     s = malloc(NUM * sizeof(*s)); 
  3. Instead of this scanf("%d", &(s+i)->ID); , the following may be easier to understand:

     scanf("%d", &s[i].ID); 
  4. Same here:

     printf("Student ID = %d\\n", s[i].ID); 
  5. Most importantly, what Nabla said.

typedef struct STUDENT
{
    int ID;
    char *name;
    char *grade;
};

Here name and grade character type pointer. so when you malloc structure you also have to malloc name and grade too

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