【发布时间】:2022-01-22 03:18:15
【问题描述】:
我目前正在学习 C 并尝试编写一个函数来标记由空格分隔的段落/字符串并返回一个包含所有标记的数组。我被卡住了,因为我无法弄清楚为什么某些令牌会携带不在原始字符串中的符号。有人可以帮我弄清楚我的代码有什么问题吗?另外,我不想在代码中添加额外的库或使用 strtok() 等函数。
char **tokenizeParagraph(char *paragraph) {
char *ptr = paragraph;
char words[MAX_WORDS][MAX_WORDLENGTH];
int wordIndex = 0;
int wordLen = 0;
while (*ptr) {
wordLen = 0;
while (*ptr && *ptr != ' ') {
wordLen++;
ptr++;
}
if (wordLen > 0) {
strncpy(words[wordIndex], paragraph, wordLen);
printf("%s\n", words[wordIndex]);
wordIndex++;
}
ptr++;
paragraph = ptr;
}
return words;
}
这是一个演示结果:
tokenizeParagraph("I'm currently learning C and trying to write a function to tokenize a paragraph/string delimited by spaces and return an array with all the tokens.");
非常感谢!
已编辑:
@Sourav Kannantha B 和@Finxx 建议的动态内存方法非常有用。但是由于我不想添加
char words[MAX_WORDS][MAX_CHARS];
void tokenizeParagraph(char words[MAX_WORDS][MAX_CHARS], char *paragraph)
【问题讨论】:
-
一方面,数组,单词,是在堆栈上分配的,返回它是未定义的行为。阅读有关堆与堆栈的信息
-
除了已诊断的其他问题之外,我看不到您在哪里终止字符串。
-
strncpy的使用可能是您的错误的来源。永远不要使用该功能。详情见Is strcpy dangerous and what should be used instead?
标签: arrays c string computer-science tokenize