Reputation: 18916
The title is a little confusing, but it's hard to describe.
In our c method:
char* wc(char** cmds, char** stringstoread, char** filename, char* result)
{
char arr[4];
int count = 0;
while(*(cmds) != NULL)
{
if(strcmp(*(cmds), "-l") == 0) // Check each commands
arr[count++] = 'l';
else if(strcmp(*(cmds), "-c") == 0)
arr[count++] = 'c';
else if(strcmp(*(cmds), "-m") == 0)
arr[count++] = 'm';
else if(strcmp(*(cmds), "-w") == 0)
arr[count++] = 'w';
cmds++;
}
if(count == 0)
{
arr[0] = 'l', arr[1] = 'c', arr[2] = 'm',arr[3] = 'w';
}
while((*stringstoread) != NULL)
{
printf("inputs are %s \n", *(stringstoread));
stringstoread++;
}
return result;
}
We are in debug mode atm, but as of now, we can't figure out why the last while loop prints out this:
inputs are input 1
inputs are input 2
inputs are -l
inputs are -w
inputs are -c
inputs are -m
we dont know how -l, -w -c and -m got into stringstoread, when the method is called like this:
char tresult[10000];
char *tcmds[] = { "-l", "-w", "-c", "-m"};
char *tinput[] = {"input 1 \n\n", "input 2 \n\n"} ;
char *tfilename[] = {"fil 1", "fil 2"} ;
char *tmp = wc(tcmds, tinput, tfilename, tresult);
It's a little messy but hope someone can help, we are new to C, so think we are running into a standard misunderstanding of the language.
Upvotes: 2
Views: 122
Reputation: 693
Another solution would be to pass the number of items in each array. If you do that, the signature should be changed to:
char* wc(char** cmds, int cmdCount, char** stringstoread, int stringStoreCount, char** filename, int fileNameCount, char* result);
If you do it this way, you must omit the NULL termination. Of course, the condition inside the 'while' loop is also different then.
Upvotes: 0
Reputation: 612884
You need to null terminate your arrays. Like this:
char *tcmds[] = { "-l", "-w", "-c", "-m", NULL};
char *tinput[] = {"input 1 \n\n", "input 2 \n\n", NULL} ;
char *tfilename[] = {"fil 1", "fil 2", NULL} ;
The reason being you are looping over these arrays until you encounter a null value. But since the arrays as defined in your program don't end in a null value, you loop off the end of them.
When your loops run off the end, you now have undefined behaviour, Anything could happen. What actually happens is that the compiler lays out the arrays adjacent to each other and you run off the end of one and into the adjacent one.
I've not checked anything else in your code. No doubt there are more errors, but I think this is the explanation for the main point of this question.
Upvotes: 5