0

while doing Pset2 Caesar, I came across this strange situation where my plaintext would change whenever my ciphertext changes.

Ultimately my program compiles and passes check50, however, if the problem had required us to print both the original plaintext and the new ciphertext at the end, my code would've failed.

I've pasted my code below (but only the part that is relevant for this question now, and some values changed for simplicity = e.g. im using 1 as the key in this example).

So my question is this:

Even though I specify that only ciphertext[i] should change for each iteration of the loop, why is it that my plaintext[i] changes as well?

Thanks in advance everyone!

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

char rotate(int n, char c);
int main(void)
{
    string plaintext = get_string("Plaintext: ");
    string ciphertext = plaintext;

    //rotate each character of plaintext by 1 to become ciphertext
    for (int i = 0; i < strlen(ciphertext); i++)
        {
            char ciphercharacter = rotate(1, ciphertext[i]);
            ciphertext[i] = ciphercharacter;
        }

    printf("Plaintext: %s\n", plaintext);
    printf("Ciphertext: %s\n", ciphertext);
}


//rotate each character of plaintext by key to become ciphered character
char rotate(int n, char c)
{
    char cipheredcharacter;
    if (isupper(c))
    {
        cipheredcharacter = (c - 65 + n) % 26 + 65;
    }
    else if (islower(c))
    {
        cipheredcharacter = (c - 97 + n) % 26 + 97;
    }
    else
    {
        cipheredcharacter = c;
    }
    return cipheredcharacter;
}

1 Answer 1

0

Here's the issue:

string ciphertext = plaintext;

This doesn't create a new string that's stored in a new part of memory. It copies the memory address of plaintext to ciphertext. In other words, both are pointers and both point to the same memory. Change the contents of one and you change both.

The code needs to create a string var, ciphertext, of the same length as plaintext (dont forget the EOS marker). If you then want to copy the string, use the strcpy() function.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thanks for the explanation!
    – Darren
    Commented Apr 2, 2022 at 3:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .