I've finished the pset2 Vigenère problem, but encountered unwanted behaviour.

So, I got the plaintext from user input and wanted to copy the value to another variable, which is to be changed further on in order to keep the original input.

        string plaintext = get_string();
        string ciphertext = plaintext;

But now, after a character in ciphertext is enciphered and changed, the plaintext changes as well.

        ciphertext[i] = (((plaintext[i]-ulswitch)+shiftlength)%26)+ulswitch;

Why is that and how can I prevent it? Thanks

1 Answer 1


string type vars are actually pointers to char arrays. When you do the following assignment,

    string ciphertext = plaintext;

you are actually assigning the address of the string plaintext to ciphertext. Both vars point to the same string, so anything you do to one is being done to the other - they are the same actual string.

Strings can't be copied simply by using the '=' operator. That usually has the effect of simply copying the pointer to the string. If you want to make a copy of a string, you need to use the strcpy() function or one of it's cousins. I'll leave it to you to look up the usage.

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

  • Thanks, will do.
    – Julian
    Commented May 28, 2017 at 20:43

You must log in to answer this question.

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