0

I am trying to write simple program to collect data for certain number of students and output it in the end. After I enter data for one student, my program crashes.

Here is the code:

#include <stdio.h>
#include <stdlib.h>
typedef struct Student Student;
struct Student{
    char name[20];
    char lastname[20];
    int age;
};

main() {
    int i;
    int n;
    scanf("%d",&n);


    Student *pStudents = NULL;
    pStudents = (Student*)malloc(n*sizeof(Student));

    for(i=0;i<n;i++) {
        printf("Enter the students name: \n");
        scanf("%s",(pStudents+i)->name);
        printf("Enter lastname: \n");
        scanf("%s",(pStudents+i)->lastname);
        printf("Enter age: \n");
        scanf("%d",(pStudents+i)->age);
    }

    for(i=0;i<n;i++) {
        printf("%s",(pStudents+i)->name);
        printf("%s",(pStudents+i)->lastname);
        printf("%d",(pStudents+i)->age);
    }

} 

Thanks in advance.

Jay
  • 23
  • 1
  • 3
  • The error was obviously the scanf but why are you using (pStudents+i) instead of pStudents[i]? It would at least show that pStudents is an array. – Maxime Chéramy Jun 23 '13 at 15:47
  • Right. I forgot pointer is same thing as array. I am still new to pointers, but this certainly makes the code more easier to read. – Jay Jun 23 '13 at 15:53
  • Assigning `NULL` to `pStudents` it totally redundant; the return value of `malloc()` overwrites is immediately. – meaning-matters Jun 23 '13 at 15:56
  • Also, don't cast the return of the `malloc()`. http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Maxime Chéramy Jun 23 '13 at 15:57
  • Thanks maxime, I am following the wrong book I guess. – Jay Jun 23 '13 at 16:01

1 Answers1

5
   scanf("%d",(pStudents+i)->age);

the argument of scanf must be of a pointer type.

Change (pStudents+i)->age to &(pStudents+i)->age.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Works! SO I assume -> operator is same as . but also dereferences ? – Jay Jun 23 '13 at 15:49
  • @Jay you use `.` for accessing a member of a struct variable (e.g. `struct Student variable`), and `->` when you're having a pointer to a struct (e.g. `struct Student *pointerVariable`). – meaning-matters Jun 23 '13 at 15:52
  • 1
    @Jay `s->a` is syntactic sugar for `(*s).a` – ouah Jun 23 '13 at 15:53
  • `pStudents` is a pointer to the first Student structure. `pStudents+i` is the address to the i-th element of your table. `(pStudents+i)->age` is the variable you want to modify. However, scanf require the address of that variable, that's why you need that extra `&`. – Maxime Chéramy Jun 23 '13 at 15:53