簡體   English   中英

如何將 int 或 char 復制到字符串元素中? 我在使用指針和轉換時遇到問題

[英]How do you copy an int or a char into a string element? I'm having trouble with pointers and casting

我不想讓以下函數打印出字符串中每個元素的加密版本,而是希望將每個加密數字傳遞到一個新字符串中,然后返回一個指向該新數組的指針。

void encrypt(int key, char *plaintext)
{
    int length = strlen(plaintext);

    for (int i = 0; i < length; i++)
    {
        if isupper(plaintext[i])
            printf("%c", (((plaintext[i] + key) - 'A') % 26) + 'A');
        else if islower(plaintext[i])
            printf("%c", (((plaintext[i] + key) - 'a') % 26) + 'a');
        else
            printf("%c", plaintext[i]);
    }
}

我編寫了以下函數,但在 clang 中出現以下錯誤:

第 12 和 14 行:

從“int”分配給“char *”的不兼容整數到指針轉換

第 16 行:

從'char'分配給'char *'的不兼容整數到指針轉換; 用 & 取地址

我是指針的新手,無法弄清楚為什么我的方法不起作用。 在第 12 和 14 行,我嘗試將公式的結果轉換為字符但無濟於事。

char * encrypt(int key, char *plaintext)
{
    int length = strlen(plaintext);
    char *cipher[length];
    char element;
    
    for (int i = 0; i < length; i++)
    {
        element = (char) &plaintext[i];

        if isupper(element)
            cipher[i] = (((element + key) - 'A') % 26) + 'A'; // Line 12 error
        else if islower(element)
            cipher[i] = (((element + key) - 'a') % 26) + 'a'; // Line 14 error
        else
            cipher[i] = element; // Line 16 error
    }

    return cipher[0];
}

如何將 int 或 char 復制到字符串元素中?

在哪里形成結果?

char *cipher[length]; 是一個指針數組,而不是預期的char數組。 cipher[i] = (((element + key) - 'A') % 26) + 'A'; 正試圖將一個整數分配給一個指針。

這個數組在函數結束時不再存在,也不是要return東西。

相反,請考慮傳入目的地:

// char * encrypt(int key, char *plaintext)
void encrypt(int key, const char *plaintext, char *cipher) {
  ...
     cipher[i] = (plaintext[i] - 'A' + key) % 26 + 'A';
}

// sample call
char plain[] = "Hello";
char cipher[sizeof plain];
int key = 1;
encrypt(key, plain, cipher)

'\\0'終止

空字符附加到目標

// after the loop
cipher[i] = '\0';

高級:減少鍵

使用int key ,當key < 0或接近INT_MAX時會出現INT_MAX 在循環之前將其減少到 [0...26)。

key %= 26;
if (key < 0) key += 26;

提示:這允許通過調用-key使用相同的函數進行解密。

次要:查找空字符

簡化代碼,使用正確的數組索引類型來處理字符串。

//int length = strlen(plaintext);
...
// for (int i = 0; i < length; i++)

size_t i;
for (i = 0; plaintext[i] != '\0'; i++)

高級:其他

僅供參考,不詳述。

  • 語言環境
  • 非 ASCII
  • char

暫無
暫無

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

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