Reputation: 23
I am working on a code in C that, based on a 26-character key input by the user in command line (ex: BCDEFGHIJKLMNOPQRSTUVWXYZA), encrypts a source message (plaintext) to an encrypted message (ciphertext) by replacing each letter of the source with the letter contained in the key at the i position, where i is the position of the source message letter in the classic alphabet. Uppercase and lowercase should be kept.
The expected output is the following: plaintext: "Hello" ciphertext: "Ifmmp"
To do this, I need an "upkey", a string made of the uppercase characters the user input as key, and a "lowkey", a string made of the lowercase characters the user input as key.
Example: upkey = argv[1] = [BCDEFGHIJKLMNOPQRSTUVWXYZA] lowkey = [bcdefghijklmnopqrstuvwxyza]
I append here below the piece of code that is giving me problems. In the cyle below, what I aim to do is to simply iterate the upkey and to replace each i character of it with the correspondant lowercase character, under the hypothesis the key the user input is made of uppercase only, as in the example above (argv[1] = [BCDEFGHIJKLMNOPQRSTUVWXYZA]).
string upkey = argv[1]; //key uppercase
string lowkey = upkey; //key lowercase temporary initialized as upkey
//generate lowkey
for (int i = 0, n = strlen(upkey); i < n; i++)
{
lowkey[i] = upkey[i] + 32; //convert to lowercase
}
What happens when I run it, is that both lowkey and upkey are manipulated.
i=0:
lowkey = [bCDEFGHIJKLMNOPQRSTUVWXYZA] //correct
upkey = [bCDEFGHIJKLMNOPQRSTUVWXYZA] //why?!
i=1:
lowkey = [bcDEFGHIJKLMNOPQRSTUVWXYZA] //correct
upkey = [bcDEFGHIJKLMNOPQRSTUVWXYZA] //why?!
and so on.
Can anyone please explain me what I am not seeing?
Upvotes: 0
Views: 106
Reputation: 311068
The reason of the problem is that the both pointers upkey
and lowkey
points to the same string argv[1]
string upkey = argv[1]; //key uppercase
string lowkey = upkey; //key lowercase temporary initialized as upkey
The last line is equivalent to
string lowkey = argv[1]; //key lowercase temporary initialized as upkey
You need to allocate an array for lower case letters. If your compiler supports variable length arrays then you could write
#include <string.h>
#include <ctype.h>
//...
string upkey = argv[1]; //key uppercase
size_t n = strlen( upkey );
char lowkey[ n + 1 ]; //key lowercase temporary initialized as upkey
lowkey[ n ] = '\0';
and then
//generate lowkey
for ( size_t i = 0; i < n; i++ )
{
lowkey[i] = tolower( ( unsigned char )upkey[i] ); //convert to lowercase
}
If the compiler does not support VLAs then you need to allocated memory dynamically like
string lowkey = malloc( n + 1 );
lowkey[ n ] = '\0';
Upvotes: 1