我知道这个问题经常被问到,但没有其他问题 问题很有帮助。我有密码
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/