簡體   English   中英

C 中的本地 scope

[英]Local scope in C

我在 C 中有這樣的東西:

string getCipherText(string text, int key) {
    string cipherText = "";
    printf("Plaintext: %s, key: %i\n", text, key);

    key = key % 26;

    for (int i = 0; i < strlen(text); i++) {
        if ((text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= 'a' && text[i] <= 'z')) {
            text[i] = (int) text[i] + key;
        }
        cipherText +=  text[i];
    }
    return cipherText;
}

為什么我返回的密文字符串是空的? 它不是 for 循環中的同一個變量嗎? 它是來自EdX https://ide.cs50.io的雲 IDE,它們在cs50.h中有一個字符串類型。

假設該stringchar*的別名, cipherText += text[i]; 不是連接字符串而是移動指針。

您應該像這樣分配一個緩沖區並將結果存儲在那里:

string getCipherText(string text, int key) {
    size_t len = strlen(text):
    string cipherText = malloc(len + 1);
    if (cipherText == NULL) {
        fputs("malloc() failed!\n", stderr);
        return NULL;
    }
    printf("Plaintext: %s, key: %i\n", text, key);

    key = key % 26;

    for (int i = 0; i < len; i++) {
        if ((text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= 'a' && text[i] <= 'z')) {
            text[i] = (int) text[i] + key;
        }
        cipherText[i] =  text[i];
    }
    cipherText[len] = '\0';
    return cipherText;
}

由於您正在直接修改“text”參數的內容,因此您可以刪除對“ciphertext”變量的所有引用,並且只需

return text;

在最后。 這樣做的好處是“文本”字符串已經存在於調用 function 中,並且肯定在調用 function 的 scope 中。

如果這是 C,那么 C 在語言中沒有類型string

它可以通過typedef或其他“詭計”來創建。

但是該語言支持使用+=將字符串連接在一起,如下所示:

cipherText +=  text[i];

我想名稱string表示以下 typedef 名稱

typedef char *string;

因此在這個聲明中

string cipherText = "";

聲明了一個指向字符串文字""的指針。

所以在這個聲明中

cipherText +=  text[i];

指向字符串文字""的指針使用指針算法增加text[i]的 integer 值。 那就是指針不指向任何地方。指針指向的位置沒有有效的 object。 因此,function 調用未定義的行為。

此語句中還有另一個錯誤

text[i] = (int) text[i] + key;

因為右手邊的表達式如果表現得像有符號字符類型,可能會導致字符類型溢出。

在任何情況下,實現都不符合 function 聲明。

function 聲明意味着必須在不創建任何其他字符數組的情況下“就地”更改傳遞的字符串。

否則,function 參數應聲明為const char *text ,因為在創建原始字符串的修改副本時,原始字符串本身不會被修改。

暫無
暫無

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

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