Hi all,
I'm puzzled...
I've got a main function as follows:
Code:
...
int main()
{
char* cmdv[20];
int i;
for(i=0;i<20;i++)
cmdv[i] = NULL;
int cmdc = 0;
prompt_user(&cmdc, cmdv);
if(cmdc>0)
{
...
prompt_user is a function defined in a static library as follows:
Code:
#include <stdio.h> //for NULL
#include <unistd.h>
#include <string.h>
#define MAXSIZE 256
void prompt_user(int *cmdc, char *cmdv[])
{
char userInput[MAXSIZE];
int nread;
char *k;
if(write(STDOUT_FILENO,"user: ",6)<0){
perror("write");
exit(1);
}
nread = read(STDIN_FILENO, userInput, MAXSIZE-1);
if(nread<0){
perror("read");
exit(1);
}
userInput[nread] = '\0';
(*cmdc) = 0;
k = userInput;
while((cmdv[*cmdc]=(char*)strtok(k, " \n"))){
k = NULL;
(*cmdc)++;
}
}
The idea is that main calls prompt_user to fill in an array cmdv[].
The thing that confuses me is that if I print cmdv[0] in the code for prompt_user, then I see what I typed in; however, if I print cmdv[0] in main after returning from the call to prompt_user, I see junk.
main makes a call to itself in the end and oddly enough, the second time it runs it works properly (i.e. cmdv[0] has the expected value after returning from the call to prompt_user.
If you need further information please let me know, the code for the main function is quite long because it compares the value of cmdv[0] to different strings so I didn't post the whole thing. Also, I don't want to post all of the main function because this is an assignment so I'm not allowed to post the whole thing of course...
Is anybody able to see what's going on here?
Thanks!