yt123
yt123

Reputation: 11

the int value changed in For loop without being calculated

i am new to c, and I am building a cipher text converter. I have a main function to take a Key value (int k) from the user and pass that value to this function:

int ciphertextCoverter (int k)
{
    printf("key=%i\n",k);
    char ciphertext[] = "";
    string plaintext = get_string("plaintext: ");

    for (int n = 0, x = strlen(plaintext); n < x; n++)
    {
         printf("key in FOR loop: %i",k);
        if isupper(plaintext[n])
        {
            printf("key in IF loop: %i",k);
            ciphertext[n] = (plaintext[n] - 'A'+ k ) % 26 + 65;

            printf("plaintext- %i %c %i %i %i %i %i\n",k, plaintext[n],plaintext[n], plaintext[n]-'A', (plaintext[n] - 'A'+ k), (plaintext[n] - 'A'+ k) % 26, (plaintext[n] - 'A'+ k) % 26+ 65);
        }
        else
        {
           ciphertext[n] = (plaintext[n] - 'a'+ k) % 26 + 97;

        }

    }
     printf("ciphertext: %s\n",ciphertext);
    return 0;

}

I used printf to find out that the value of int k which I passed on from the main function has changed value in the for loop, but I want to stay as a const. Please help me! what have I done wrong?

Upvotes: 1

Views: 86

Answers (2)

user15375057
user15375057

Reputation:

You have declared character array of size 1. And you are storing x characters in ciphertext[]. First declare array of any size or create array dynamically.

char ciphertext[] = "";

Upvotes: 0

William Pursell
William Pursell

Reputation: 212248

You are declaring ciphertext as an array of size 1, so you cannot write any data to it. Give it some size; something like:

string plaintext = get_string("plaintext: ");
char ciphertext[strlen(plaintext) + 1];

should work. Just remember to write the null terminator at the end: ciphertext[x] = '\0'

Upvotes: 3

Related Questions