我有一个类,它通过将一个char *分成句子来返回一个char **。我可以分配内存并在某个时间点给它值,但是当我尝试返回它时,它完全没有了。
char **makeSentences(char *chapter, int *nSentences){
int num = *nSentences;
char* chap = chapter;
char **sentences;
sentences = (char**) malloc(sizeof(char*) * num);
int stops[num + 1];
stops[0] = 0;
int counter = 0;
int stop = 1;
while (chap[counter] != '\0'){
if (chap[counter] == '.'){
stops[stop] = counter + 1;
printf("Place: %d\nStop Number: %d\n\n", counter, stop);
stop++;
}
counter++;
}
for (int i = 0; i < num; i++){
int length = stops[i+1] - stops[i];
char characters[length+1];
memcpy(characters, &chap[stops[i]], length);
characters[length] = '\0';
char *sentence = characters;
sentences[i] = sentence;
printf("%s\n",sentence);
printf("%s\n", sentences[i]);
}
char* testChar = sentences[0];
printf("%s\n", sentences[0]);
printf("%s]n", testChar);
return sentences;
}
最后两行打印行不打印除换行符之外的任何内容,而完全相同的行(在for循环中)按预期打印。这是怎么回事?
答案 0 :(得分:2)
问题在于这三行:
char characters[length+1];
char *sentence = characters;
sentences[i] = sentence;
在此处保存指向本地变量的指针。变量characters
将在循环的每次迭代中超出范围,留下一个“数组”的杂散指针。
虽然在C中不是标准,但几乎所有系统都有strdup
函数,通过调用malloc
和strcpy
来复制字符串。我建议你使用它(或实现你自己的)。