First some sample code:

 1 // preliminary headers and such :-)

30 string key = argv[1];  // BAZ
   // validate key

35 string plain = GetString();  // test
38 string cipher = plain;
   // loop through the plaintext converting it and placing it into the cipher string
61    printf("plain: %i, plain[i]"); // prints out 116 (t) assuming i=0
62    cipher[i] = (plain[i] - 'a' + key[v] - 'a') % 26 + 'a';
63    printf("plain: %i, plain[i]"); // prints out 85 (U)
82 // the final printout of "test" using "BAZ" as the keyword is "U_lU"

Why is the value of plain[i] changing? Does setting cipher = plain work both ways? I thought assigning a variable to another variable was a one way thing, kind of like making a copy. To my knowledge line 62 should't do anything to the variable plain, just alter the contents of cipher[i]. BTW - I've copied the formula to it's own .c file and hard coded the key and individual characters into the formula and it seems to work just fine. The problem is plain[i] changes before the actual formula is run.

The reason I set the value of cipher to plain in line 38 is that I have to initialize the string. If I use NULL (as clang suggests) or just empty "", its length can't be altered. I tried using cipher[strlen(plain)] since a string is an array of chars, but it throws 8 errors back at me.

Also, oddly enough, the upper case version of the formula works just fine. I didn't include it here, because it seems irrelevent.

Thanks in advance.

1 Answer 1


when you do string cipher = plain you aren't creating a copy, but just another representation.

You don't really need cipher at all. You can just printf your new value using somthing like

printf("%c", (plain[i] - 'a' + key[v] - 'a') % 26 + 'a');

Don't forget that you need to handle upper and lowercase differently. the above only works for lowercase.

You must log in to answer this question.

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