I have a const char*
which represents a path I want to split it into an array of strings at character /
so I can do the search step by step.
I tried doing
char* str2 = strtok(str1,"/")
but my compiler returns a
warning: initialization discards 'const' qualifier from pointer target type
How can I do the split without any warning?
strtok(3)
and strtok_r(3)
mutate the string in place, which prevents you from passing a const string. You will want to pass a copy anyway, as you don't want your initial string to be mutated and become unusable.
Here's how you can do it with strdup(3)
:
char* strtmp = strdup(str1);
char* str2 = strtok(strtmp,"/");
// Use str2 here
free(strtmp);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.