簡體   English   中英

C ++下/上字符char指針

[英]C++ tolower/toupper char pointer

你們知道為什么以下代碼在運行時崩潰嗎?

char* word;
word = new char[20];
word = "HeLlo"; 
for (auto it = word; it != NULL; it++){        
    *it = (char) tolower(*it);

我正在嘗試將char *(字符串)小寫。 我正在使用Visual Studio。

謝謝

您無法將itNULL進行比較。 相反,您應該將*it'\\0'進行比較。 或者更好的是,使用std::string ,不必擔心它:-)

總之,在遍歷C樣式的字符串時。 您應該循環播放,直到看到的字符'\\0'為止。 迭代器本身永遠不會為NULL ,因為它只是指向字符串中的一個位置。 迭代器具有可以與NULL比較的類型這一事實是您不應該直接接觸的實現細節。

此外,您正在嘗試寫入字符串文字。 這是一個禁忌:-)。

編輯 :@Cheers和hth指出。 -Alf,如果給定負值, tolower可能會破裂。 很遺憾,我們需要添加一個強制轉換,以確保在喂入Latin-1編碼的數據或類似數據時,此轉換不會中斷。

這應該工作:

char word[] = "HeLlo";
for (auto it = word; *it != '\0'; ++it) {
    *it = tolower(static_cast<unsigned char>(*it));
}

您將word設置為指向字符串文字,但是文字是只讀的,因此當您分配給*it時,這將導致未定義的行為。 您需要在動態分配的內存中制作一個副本。

char *word = new char[20];
strcpy(word, "HeLlo");

同樣在循環中,您應該比較*it != '\\0' 字符串的結尾由字符表示為空字節,而不是指針為空。

給定代碼(在寫這篇文章時):

char* word;
word = new char[20];
word = "HeLlo"; 
for (auto it = word; it != NULL; it++){        
    *it = (char) tolower(*it);

該代碼以兩種不同的方式具有未定義的行為 ,如果僅文本數據稍有不同,則該代碼也將以第三種方式具有UB:

  • 緩沖區溢出。
    連續條件it != NULL直到it在地址范圍的末尾環繞指針(如果確實如此)時,才會為false

  • 修改只讀存儲器。
    指針word設置為指向所述第一char的字符串的文字,然后用該字符串的循環迭代和分配給每個char

  • 將可能的負值傳遞到tolower
    char分類函數需要一個非負參數,或者特殊值EOF 在ASCII或無符號char類型的假設下,此字符串可以很好地與字符串"HeLlo"使用。 但是通常,例如,使用字符串"Blåbærsyltetøy" ,將每個char值直接傳遞給tolower都會導致傳遞負值; chchar類型正確的調用是(char) tolower( (unsigned char)ch )

此外,代碼還會發生內存泄漏 ,方法是使用new分配一些內存,然后忘記它。

正確編碼表面意圖的正確方法:

using Byte = unsigned char;

auto to_lower( char const c )
    -> char
{ return Byte( tolower( Byte( c ) ) ); }

// ...
string word = "Hello";
for( char& ch : word ) { ch = to_lower( ch ); }

關於如何使用以空終止的c字符串和poitners解決問題的方法,已經有了兩個不錯的答案。 為了完整起見,我建議您使用c ++字符串的方法:

string word;           // instead of char* 
//word = new char[20]; // no longuer needed: strings take care for themseves
word = "HeLlo";        //  no worry about deallocating previous values: strings take care for themselves
for (auto &it : word)  // use of range for, to iterate through all the string elements      
    it = (char) tolower(it);

它崩潰是因為您正在修改字符串文字。

有一個專用的函數供使用, strupr使字符串大寫, strlwr使字符串小寫。

這是一個用法示例:

char str[ ] = "make me upper";
printf("%s\n",strupr(str));


char str[ ] = "make me lower";
printf("%s\n",strlwr (str));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM