Aneesh Kandrakota
Aneesh Kandrakota

Reputation: 5

cs50 pset2 caesar, either getting segmentation fault or incompatible conversion

This is my code so far, for the 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;
    }
}

The problematic part is only the ciphertext string. With this current code it says conversion from char b to string chiphertext[i] is incompatible. So I tried removing the array when intializing and initialized it to NULL but then it said segmentation fault. And there is also another error where it says it can't print ciphertext because format suggests it's a character while I put a string stronghold. What do I do?

Here's a picture of the error.

Upvotes: 0

Views: 74

Answers (1)

Daniel Walker
Daniel Walker

Reputation: 6760

Since string is a typedef for char*, ciphertext is an array of char pointers. Therefore, assigning a char when it expects a pointer is going to have bad results.

You really don't want ciphertext to be an array of strings. You want it to be another string with the same size as plaintext. You can do this with

string ciphertext=malloc(strlen(plaintext)+1); // The +1 is for the null-terminator.

Also, I would calculate strlen(plaintext) once inside of twice. Do

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

Upvotes: 2

Related Questions