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)
I have googled this and I think it is because a while loop in Bash creates a subshell, not too sure.
Any help would be much appreciated (please have patience I am only a student!!)
Using Mac OSX mountain lion Xcode 4 gcc
Code:
#include <stdio.h>
#include <limits.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
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 < 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 <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);
}
nodes
is an array of typeNode
, notNode *
, so you can't doNode newNode = {one,two}; nodes[count]= newNode;
. – Vicky Apr 11 at 13:05