c - C中的strtok段错误

标签 c strtok

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

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 复制您正在处理的字符串。然后你可以复制出子字符串。

关于c - C中的strtok段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47358036/

相关文章:

清除Libcurl中的cookie文件

c - 如何读取/写入 RSA 结构中的公钥

计算C中三角形的边长

c - 数组值不更新

c - Nicelabel 算法超过 MAX TICKS

代码遇到段错误错误。如何修复?

c - strtok() 没有按预期工作

c - 从不同的文件读取并在字符串上使用 strtok

c - strtok()函数的实现

c - Strtok 使用并查找第二个元素