[英]Reverse Words in a String in C
因此,基本上,在本練習中,我應該反轉給定字符串中的每個單詞。 單詞被認為包含字母數字字符,任何非字母數字字符都將以單詞結尾。 例如“無論如何,這都是示例字符串”。 反過來說,“就是這樣”。
我真的很難弄清楚我編寫的代碼出了什么問題。 該代碼似乎可以正常工作,但是當我將其發送到測試服務器時,它給出了Valgrind錯誤。
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void reversed_words(char *str)
{
char word[100];
char *temp;
char *zet;
temp=str;
int k=0;
while(*temp) //processing complete string
{
if(isalnum(*temp))
{
while(isalnum(*temp)) //extracting word from string
{
word[k]=*temp;
k++;
temp++;
}
word[k]='\0';
k=0;
strrev(word); // Reverses the string
zet=word;
while (*zet) // Copying the reversed word into original string
{
*str = *zet;
zet++;
str++;
}
while (!isalnum(*str)) // Skipping all non-alphanumeric character(s)
{
str++;
}
}
temp++;
}
}
因此,我收到以下錯誤消息:“使用大小為8的未初始化值”和“未初始化值是由堆棧分配創建的”。 我不知道錯誤來自哪里,我希望有人可以幫助我解決這個問題。 提前致謝。
這是對函數的更改,它進行了最少的更改以修復原始代碼中的錯誤。 具體進行了兩項更改:1)在while的底部用一個簡單的str替換了最后一個while循環(從先前的文章進行了修改)。 正確的答案已經被計算出來,並且該分配使字符串向前移動,而沒有另一個while循環,該循環可能會導致結尾下降。 2)在temp++
周圍放置一個else,因為當發現一個單詞時不應該這樣做,否則您可以結束。
void reversed_words(char *str)
{
char word[100];
char *temp;
char *zet;
temp=str;
int k=0;
while(*temp) //processing complete string
{
if(isalnum(*temp))
{
while(isalnum(*temp)) //extracting word from string
{
word[k]=*temp;
k++;
temp++;
}
word[k]='\0';
k=0;
strrev(word); // Reverses the string
zet=word;
while (*zet) // Copying the reversed word into original string
{
*str = *zet;
zet++;
str++;
}
}
else
{
temp++;
}
str = temp;
}
}
這可能是一個問題:
zet = word;
while (*zet) // Copying the reversed word into original string
{
*str = *zet;
zet++;
str++;
}
while (!isalnum(*str)) // Skipping all non-alphanumeric character(s)
{
str++;
}
當處理最后一個單詞時,它從第一個while
循環中出來,其中str
指向輸入字符串末尾的非字母垃圾或字符串末尾的'\\0'
終止符。 無論哪種情況,終止符都不是字母數字,因此第二個while
循環將繼續讀取,直到找到恰好是字母數字的字節為止,該字節可能在未初始化的內存中。
您的strrev
或main
功能中也可能有問題,但沒有發布它們。
考慮如果將“單詞”長於99個字符的字符串傳遞給該函數,將會發生什么,這也是一個好主意。
“使用大小為8的未初始化值”的原因可能是您沒有立即初始化char指針(temp和zet),而在64位系統上,char指針的大小實際上為8(字節)。 如果沒有用於初始化指針的值,則應始終確保將其初始化為0,以使您知道它不指向任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.