我目前正在學習 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.");
錯誤演示
非常感激!
uj5u.com熱心網友回復:
@Finxx 已經建議的已經足夠好了。但是如果 wordLen 變化很大,你仍然可以改進它。
char **tokenizeParagraph(char *paragraph) {
char *ptr = paragraph;
char** words = malloc(sizeof(char*) * MAX_WORDS);
int wordIndex = 0;
int wordLen;
while (*ptr) {
wordLen = 0;
while (*ptr && *ptr == ' ') {
ptr ;
}
paragraph = ptr;
while (*ptr && *ptr != ' ') {
wordLen ;
ptr ;
}
if (wordLen > 0) {
words[wordIndex] = malloc(sizeof(char) * wordLen 1);
strncpy(words[wordIndex], paragraph, wordLen);
words[wordIndex][wordLen] = '\0';
printf("%s\n", words[wordIndex]);
wordIndex ;
}
}
for(;wordIndex < MAX_WORDS; wordIndex ) {
words[wordIndex] = NULL;
}
return words;
}
另外,請注意strncpy不添加終止 NUL 字符。這可能是輸出中出現隨機字符的原因。
另外,不要忘記free呼叫者函式分配的記憶體。:
int main() {
...
char** words = tokenizeParagraph(para);
...
for(int i = 0; i < MAX_WORDS; i ) {
free(words[i]);
}
free(words);
...
return 0;
}
uj5u.com熱心網友回復:
您正在堆疊上創建變數words并在堆疊上回傳指向 this 的指標。但是,當您從函式回傳時,堆疊不再局限于您的程式,這意味著您的指標指向的某些內容可能會發生變化,從而導致未定義的行為。為了防止這種情況,請更改此代碼:
char words[MAX_WORDS][MAX_WORDLENGTH];
有了這個:
char** words = calloc(MAX_WORDS * MAX_WORDLENGTH, sizeof(char));
這將在堆而不是堆疊上分配記憶體,盡管您需要stdlib.h包含在內。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/418541.html
標籤:
上一篇:使用OpenMP優化矩陣轉置函式
