Here is a method to implement split string by strtok
in C.
void split(char** dest, char* src, const char* del){
char* token = strtok(src, del);
while(token!=NULL){
*dest++ = token;
token = strtok(NULL, del);
}
}
I tried to test this function by main()
. The test device is asus T100(32bit OS, x64 processor) compiled by Cygwin with gcc version 4.9.2 (GCC)
int main(void){
char* str="/storage/SD:/storage/USB1";
const char* del=":";
char* arr[2];
split(arr, str, del);
return 0;
}
The result is Segmentation fault (core dumped), why?
The sizeof(char*)
is 4bytes on this test device.
If I modify
char* str="/storage/SD:/storage/USB1";
to
char str[]="/storage/SD:/storage/USB1";
everything run as expected.