I made a function that receives a string and it should return the element after "-e". For example, "show -e LENA" should return "LENA".
char *getElementAfterE(char *str) {
const char *delimiter = " ";
const char *flag = "-e";
char *result = NULL;
char *token = strtok(str, delimiter); // Get the first token
while (token != NULL) {
if (strcmp(token, flag) == 0) {
token = strtok(NULL, delimiter); // Get the next token
printf("next token: %s\n", token);
if (token != NULL) {
result = token;
}
break;
}
token = strtok(NULL, delimiter); // Get the next token
}
return result;
}
The problem is that the strtok after the if allways returns null even when the string still has tokens left.
Aparently it has to do with the string i give to the function. If i use a pointer it doesnt work:
char *str = "show -e LENA";
char *result = getElementAfterE(str);
If i use a char array it works:
char str[] = "show -e LENA";
char *result = getElementAfterE(str);
The problem is that in my program i'm giving it a pointer. Do i need to copy my pointer into a char array before giving it to the function?
strtokmodifies the provided string. It basically replaces the delimiters with NULs in order to create a proper string to return without allocating any memory.You are passing a string literal. Modifying a string literal is Undefined Behaviour.
Using
char str[] = "show -e LENA";instead creates an modifiable array.The string does not need to be in an array, but it does need to be modifiable.