“不兼容的整数到指针转换”

mat*_*ian 1 c pointers compiler-errors incompatibletypeerror cs50

由于这些错误,以下程序拒绝编译:

vigenere.c:52:31: error: incompatible integer to pointer conversion assigning to
  'string' (aka 'char *') from 'int' [-Werror,-Wint-conversion]
  ...ciphertext[i] = ((((plaintext[i] - 65) + keyword[num % keylength]) % 26) + 65);
                   ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
vigenere.c:56:31: error: incompatible integer to pointer conversion assigning to
  'string' (aka 'char *') from 'int' [-Werror,-Wint-conversion]
  ...ciphertext[i] = ((((plaintext[i] - 97) + keyword[num % keylength]) % 26) + 97);
                   ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

这是程序,旨在实现一个简单的 vigenere 密码:

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main(int argc, string argv[])
{
    if(argc != 2)
    {
        printf("Invalid input; try again!\n");
        return 1;
    }
    else if(argv[1])
    {   
        for(int i = 0, n = strlen(argv[1]); i < n; i++)
        {
            if(!isalpha(argv[1][i]))
            {
                printf("Invalid input; try again!\n");
                return 1;
            }
        }
    }

    // get plaintext from user
    string plaintext = GetString();
    string ciphertext[100];
    int num = 0;

    string keyword = argv[1];
    int keylength = strlen(keyword);

    // change key values from letters to shifts
    for(int i = 0, n = keylength; i < n; i++)
    {
        if(isupper(keyword[i]))
        {
            keyword[i] = keyword[i] - 65;
        }
        else if(islower(keyword[i]))
        {
            keyword[i] = keyword[i] - 97;
        }
    }

    for(int i = 0, n = strlen(plaintext); i < n; i++)
    {
        if(isalpha(plaintext[i]))
        {
            if(isupper(plaintext[i]))
            {   
                ciphertext[i] = ((((plaintext[i] - 65) + keyword[num % keylength]) % 26) + 65);
            }
            else if(islower(plaintext[i]))
            {
                ciphertext[i] = ((((plaintext[i] - 97) + keyword[num % keylength]) % 26) + 97);
            }
            num++;
        }
        // non-alphabetic characters
        else 
        {
            ciphertext[i] = plaintext[i];
        }
        printf("%c", ciphertext[i]);
    }
    printf("\n");
}
Run Code Online (Sandbox Code Playgroud)

我不知道为什么编译器会抛出错误,因为我有一个旧版本的程序,几个月前编译过(第 52 行和第 56 行的代码完全相同),它工作得很好。

我真的很感激任何帮助:)

小智 5

变量ciphertext是数组char*,我认为应该是:

char ciphertext[1000]
Run Code Online (Sandbox Code Playgroud)