Yeah, you can't do that.
char tempString[256];
declares a variable on the stack in the function parse_command
, that variable goes out of scope and pointers to it cease to be valid when parse_command
returns.
You need to allocate the command string on the heap, so that it will still be valid when parse_command
returns. This is one way.
parse_command(char *inTempString){
char tempString[256];
(call to function that assigns a string to tempString)
int cb = strlen(tempString)+1;
cmd1[0] = (char *)malloc(cb);
strcpy(cmd1[0], tempString);
}
You should also call free(cmd[0])
before main exits.
In addition to that, this code doesn't compile. You can't reference cmd1[0]
from inside the parse_command
function. You should be getting a type mismatch when you try and pass cmd1
into parse_command
, If you mean to return a char* from parse_command
then it should be declared to take a char** as an argument, more like this.
parse_command(char **pcmd){
char tempString[256];
(call to function that assigns a string to tempString)
int cb = strlen(tempString)+1;
pcmd[0] = (char *)malloc(cb);
strcpy(pcmd[0], tempString);
}