0

I'm trying to make a C program in which user is able to add multiple students to the list. The point of that is to create a database of students (without accessing a .txt file, It just has to be able to add students and then search for a specific student by surname in the same run, no saving).

struct student{
int semester;
char major[20];
char name[20];
};

struct person{
int id;
char surname[30];
struct student data;
}stud;

typedef struct person* st[10];
int m=0;

int add(){
printf("Type student's surname\n");
st[m]->surname=getchar(); //that's basically the part in which I need help
m=m+1;
}

While I think I can handle searching, I don't really know how to do the adding part. I want to keep it as simple as possible (I'm a freshman). My intent is to use structure person (with student nested to it) and then whenever the user calls function add they'll be able to add one student (let's say that the max is 10). My idea was to make 10 structures (struct[m]) with m rising each time function add is called, but it seems not to work the way I expected.

How can I make it happen? Any help is much appreciated.

macsob7
  • 3
  • 2
  • Try to break your task into smaller problems. Separate input from creating entries. Use constants in test routines to test your ideas. So make a function which just adds a student like strcpy(aStructInstance.surname, "test name"). Then work up to using the array. You will quickly see where your problems are. – john elemans Nov 21 '19 at 23:56
  • See [Is it a good idea to typedef pointers?](https://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) If you really intended to define an array of pointers to a structure type, it might be reasonable to define the type, but that probably wasn't what you had in mind. Did you intend to define the unused variable `stud`? – Jonathan Leffler Nov 22 '19 at 01:01

1 Answers1

2
typedef struct person* st[10];

Here you are not creating an array, you are defining a type named st which can be used to later declare a size 10 array of pointers to struct person

st[m]->surname=getchar();

Hence this part should not compile as st is a type. Also, if you want to make an array of pointers as you are doing there, you also have to allocate those structures on the heap using malloc (more info here).

I suggest you to instead allocate the structures on the stack, you can do it changing the typedef line to this:

struct person st[10];
sephiroth
  • 896
  • 12
  • 22