Note that there are some explanatory texts on larger screens.

plurals
  1. POGlobal Array doesn't update while inside while loop?
    primarykey
    data
    text
    <p>I have an array of structs, inside the while loop I add things to that array, however when I print out the array I get the wrong output? (The last element added is printed out n times, n being the number of things I added)</p> <p>I have googled this and I think it is because a while loop in Bash creates a subshell, not too sure.</p> <p>Any help would be much appreciated (please have patience I am only a student!!)</p> <p>Using Mac OSX mountain lion Xcode 4 gcc</p> <p>Code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;limits.h&gt; #include &lt;ctype.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; typedef struct{ char* one; char* two; } Node; Node nodes[100]; int count = 0; void add(char *one,char*two){ Node newNode = {one,two}; nodes[count]= newNode; printf("one: %s\n",one); printf("two: %s\n",two); count++; } void print(){ int x; for (x = 0; x &lt; 10; x++) printf("%d : (%s, %s) \n",x,nodes[x].one, nodes[x].two); } void check(char **arg) { if(strcmp(*arg, "Add") == 0) add(arg[1],arg[2]); else if(strcmp(*arg,"print") == 0) print(); else printf("Error syntax Enter either: \n Add [item1][item2]\n OR \n print\n"); } void readandParseInput(char *line,char **arg) { if (fgets (line, 512, stdin)!= NULL) { char * pch; pch = strtok (line," \n\t"); int count = 0; arg[0] = pch; while (pch != NULL) { count++; pch = strtok (NULL, " \n\t"); arg[count] = pch; } }else{ printf("\n"); exit(0); } } int main() { int i; for(i = 0;i &lt;100; i++){ nodes[i].one = "."; nodes[i].two = "."; } char line[512]; /* the input line */ char *arg[50]; /* the command line argument */ while (1) { readandParseInput(line,arg); if(arg[0] != NULL) check(arg); } return(0); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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