Hi guys I got some problems with using a function with a reference to a string as argument. I read that you should use e double pointer for this, but I can’t get it to work.
This is (partly) my code.
enum errCode { ERR_NONE = 0, ERR_EMPTY, ERR_FULL, ERR_MEM, ERR_INIT, ERR_COMMAND, ERR_UNDEFINED };
typedef enum errCode ErrCode;
typedef enum {
no = 0, add, del, src, show, exit
} Command;
int main(void) {
char stringval[50];
char stringval2[50];
ErrCode err;
Command currentCommand = no;
printf("Enter a command\n");
if (fgets(stringval, 50, stdin) != NULL) {
char *p;
if ((p = strchr(stringval, '\n')) != NULL)
*p = '\0';
}
ErrHandler(
extractCommand(¤tCommand, stringval, &stringval2)
);
printf("stringval 2 = %s.\n", stringval2);
return 0;
}
ErrCode extractCommand(Command *command, char *inputString, char **outputString) {
char *strTemp;
char *strTemp2;
//Get the first word of the string
strTemp = strtok(inputString, " ");
strTemp2 = strtok(NULL, " ");
*outputString = strTemp2;
//Check if it equals a command
if (strcmp(strTemp, "exit") == 0) {
*command = exit;
return ERR_NONE;
} else if (strcmp(strTemp, "add") == 0) {
*command = add;
return ERR_NONE;
} else if (strcmp(strTemp, "del") == 0) {
*command = del;
return ERR_NONE;
} else if (strcmp(strTemp, "src") == 0) {
*command = src;
return ERR_NONE;
} else if (strcmp(strTemp, "show") == 0) {
*command = show;
return ERR_NONE;
} else {
*command = no;
printf("%s", strTemp);
return ERR_COMMAND;
}
}
This is what my output looks like:
Enter a command
add this is a test
stringval 2 = z˜ˇøÀo‡èK‡èT¯ˇø.
I obviously want to have the second word of the inputted string, but I’m doing something wrong.
Thx for the help!
stringVal2is not initialised and is never populated: that is reason junk is being printed. There is no need in this case to pass achar**, passing achar*will work. However, this:does not copy the content of
strTemp2tooutputString: it makesoutputStringpoint to the same address asstrTemp2: usestrcpy().A double pointer,
char**for example, is commonly passed to a function when that function allocates a new buffer for the argument (which is not the case in the posted code):