Sorry for long question but I am about to go crazy here.
I am trying to write a little simulation of a social network in c language.
I'm trying to create an array of structures which each one is a user.
For 6 days, I'm trying to write the part that the program adding users and reaching the logs afterwards, and I couldn't. So I'm about to lose my mind over here.
struct myStruct { /* This is a global variable */
char *studentName;
int *bornYear;
char *school;
};
then in the main function, I create a pointer such as;
struct myStruct** students = malloc (sizeof(struct myStruct ));
int counter = 0; /* the counter of students */
by if-else if and switch-case chains, I categorize the commands. when it is asked to add a new user, a realloc the array I created:
students = realloc(students, (counter+1) * sizeof (struct students));
students[counter] = adding (*command, counter);
counter++;
the function is here:
struct myStruct adding (char theCommand[], int i){
struct myStruct *q = malloc(sizeof(struct myStruct *)); // I get a warning for this allocation
char *irrelevantChar = strtok(theCommand[], ";");
q->studentName = strtok(NULL, ",");
q->bornYear= strtok(NULL, ",");
q->school= strtok(NULL, ",");
return q;
I am sure that strtok functions are working right.
When I try to reach these structures, the program gives error on run-time (stoppes working on windows, segmentation fault on ubuntu) or I see random irrelevant data etc. I am working with this for 6 days so I have seen lots of errors. But I couldn't find the right way to create and access these structures.
In another command situation;
"command character" John Smith,George Lucas // names are just for example :)
I just wrote the following code for this situation:
printf ("\n\n%s", myStruct[0]->school;
This is just a random order, just to show that I cannot access it.
The output must be "Oxford University" or something. Instead, I get the exactly following output:
ge Lucas
So some random data. I don't know what is wrong with here either.
I must build friendships etc. so I must have access to every single structure I created.
Thanks :)
struct myStruct *q = malloc(sizeof(struct myStruct *));, you should usestruct myStruct *q = malloc(sizeof(struct myStruct));. I would suggest to use a linked list instead of reallocating everytime.