cs50 pset2 caesar,出现分段错误或不兼容的转换

cs50 pset2 caesar, either getting segmentation fault or incompatible conversion

到目前为止,这是我的代码,用于 caesar problem from problem set 2 of CS50:

int main(int argc, string argv[])
{
    if (argc == 2 && check_integer(argv[1]) == true)
    {
        int key = atoi(argv[1]);
        string plaintext = get_string("plaintext: ");
        string ciphertext[strlen(plaintext)];
        for (int i = 0, n = strlen(plaintext); i < n; i++)
        {
            char a = plaintext[i], b;
            if (a >= 'A' && a <= 'Z')
            {
                if (a + (key % 26) > 'Z')
                {
                    b = a - (26 - (key % 26));
                }
                else
                {
                    b = a + (key % 26);
                }
            }
            if ((a >= 'a' && a <= 'z'))
            {
                if (a + (key % 26) > 'z')
                {
                    b = a - (26 - (key % 26));
                }
                else
                {
                    b = a + (key % 26);
                }
            }
            ciphertext[i] = b;
        }
        printf("ciphertext: %s", ciphertext);
        return 0;
    }
    else
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
}

有问题的部分只是密文字符串。使用当前代码,它表示从 char b 到字符串 chiphertext[i] 的转换不兼容。所以我尝试在初始化时删除数组并将其初始化为 NULL 但随后它说分段错误。还有另一个错误,它说它无法打印密文,因为格式表明它是一个字符,而我放置了一个字符串据点。我该怎么办?

这里是a picture of the error。

因为 stringchar*typedefciphertextchar 指针的数组。因此,在需要指针时分配 char 会产生不好的结果。

您真的不希望 ciphertext 成为 string 的数组。您希望它是另一个与 plaintext 大小相同的字符串。你可以用

来做到这一点
string ciphertext=malloc(strlen(plaintext)+1); // The +1 is for the null-terminator.

此外,我会计算 strlen(plaintext) 一次或两次。做

n=strlen(plaintext);
string ciphertext=malloc(n+1);