繁体   English   中英

C中的strtok分段错误

[英]strtok segmentation fault error in C

我知道这个问题经常被问到,但是其他问题都没有帮助。 我有一个密码

char *hamlet[] = {"Give every man thy ear, but few thy voice.",
        "Neither a borrower nor a lender be.",
        "For loan oft loses both itself and friend",
        "And borrowing dulls the edge of husbandry.",
        "This above all: to thine own self be true."};
    int i;
    for (i = 0; i < NUM_SENTENCES; i++) {
    int size;
    char **words = splitString(hamlet[i], &size);

在另一个.c文件中

char** splitString(char theString[], int *arraySize){
int numWords = 1;
int i=0;
numWords += countSpaces(theString);
char **wordArray = malloc(numWords * sizeof(char*));

char *token;
token = strtok(theString, " ");

return wordArray;

问题是,当我链接它们并运行它时,我总是会遇到分段错误。 我相信这是内存引起的错误,因为第一代码和第二代码位于不同的.c文件中。 我真的找不到解决方法

hamlet数组的内容都是字符串文字。 这些是不可修改的,通常驻留在内存的只读部分中。 strtok函数会修改其参数,因此这就是崩溃的原因。

您需要使用strdup复制正在处理的字符串。 然后,您可以复制出子字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM