gpt4 book ai didi

android - 在 C 中通过 strtok 实现拆分字符串 - 段错误(核心转储)

转载 作者:太空宇宙 更新时间:2023-11-04 04:38:23 25 4
gpt4 key购买 nike

这里是用strtok在C语言中实现拆分字符串的方法。

void split(char** dest, char* src, const char* del){
char* token = strtok(src, del);
while(token!=NULL){
*dest++ = token;
token = strtok(NULL, del);
}
}

我试图通过 main() 测试这个函数。测试设备为asus T100(32bit OS, x64 processor) Cygwin编译,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;
}

结果是Segmentation fault (core dumped),为什么?

sizeof(char*) 在此测试设备上为4bytes

如果我修改

char* str="/storage/SD:/storage/USB1";

char str[]="/storage/SD:/storage/USB1";

一切都按预期运行。

最佳答案

C 和 C++ 中的字符串文字是不可变的。任何修改字符串文字的尝试都会导致未定义的行为。函数 strtok 更改作为参数传递给它的字符串。替换此声明

char* str = "/storage/SD:/storage/USB1";

char str[] = "/storage/SD:/storage/USB1";

来自 C 标准(6.4.5 字符串文字)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

并且从函数strtok的描述来看

4 The strtok function then searches from there for a character that is contained in the current separator string. If no such character is found, the current token extends to the end of the string pointed to by s1, and subsequent searches for a token will return a null pointer. If such a character is found, it is overwritten by a null character, which terminates the current token. The strtok function saves a pointer to the following character, from which the next search for a token will start.

还要考虑到函数 main 应具有返回类型 int

int main( void )

关于android - 在 C 中通过 strtok 实现拆分字符串 - 段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28912773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com