Note that there are some explanatory texts on larger screens.

plurals
  1. POHandling with array of structures in C
    text
    copied!<p>Sorry for long question but I am about to go crazy here.</p> <p>I am trying to write a little simulation of a social network in c language.</p> <p>I'm trying to create an array of structures which each one is a user.</p> <p>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.</p> <pre><code>struct myStruct { /* This is a global variable */ char *studentName; int *bornYear; char *school; }; </code></pre> <p>then in the main function, I create a pointer such as;</p> <pre><code>struct myStruct** students = malloc (sizeof(struct myStruct )); int counter = 0; /* the counter of students */ </code></pre> <p>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:</p> <pre><code>students = realloc(students, (counter+1) * sizeof (struct students)); students[counter] = adding (*command, counter); counter++; </code></pre> <p>the function is here:</p> <pre><code>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-&gt;studentName = strtok(NULL, ","); q-&gt;bornYear= strtok(NULL, ","); q-&gt;school= strtok(NULL, ","); return q; </code></pre> <p>I am sure that strtok functions are working right.</p> <p>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.</p> <p>In another command situation;</p> <pre><code>"command character" John Smith,George Lucas // names are just for example :) </code></pre> <p>I just wrote the following code for this situation:</p> <pre><code>printf ("\n\n%s", myStruct[0]-&gt;school; </code></pre> <p>This is just a random order, just to show that I cannot access it.</p> <p>The output must be "Oxford University" or something. Instead, I get the exactly following output:</p> <pre><code>ge Lucas </code></pre> <p>So some random data. I don't know what is wrong with here either.</p> <p>I must build friendships etc. so I must have access to every single structure I created.</p> <p>Thanks :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload