0

I am working on Caesar cipher on CS50 Week 2. I have generally wrote most part of the code but the final error message which i have not debugged was the initalizing of the string at the end. How do you initialize the string such that the error message goes away and we achieve our objective?

I tried using char string[] and string string but all yielded the same error.

My function is shown below:

//Ciphering Function
string plainToCipher(string plainText,int key)
{

int i = strlen(plainText);
string cipher;
int j = 0;
do
{

    if(plainText[j] >= 'a' && plainText[j] <= 'z')
    {
        cipher[j] = ((plainText[j] - 'a') + key) % 26 + 'a'; 
    }

    else if(plainText[j] >= 'A' && plainText[j] <= 'Z')
    {
        cipher[j] = ((plainText[j] - 'A') + key) % 26 + 'A';
    }

}while(j<i);

return cipher;

}

My error message is this:

caesar.c:71:17: error: variable 'cipher' is uninitialized when used here
  [-Werror,-Wuninitialized]
            cipher[j] = ((plainText[j] - 'a') + key) % 26 + 'a'; 
            ^~~~~~
caesar.c:64:18: note: initialize the variable 'cipher' to silence this 
warning
string cipher;
             ^
              = NULL
0

A string in C is just a pointer to the first character, the characters might be stored anywhere. You don't let cipher point anywhere, so its value could be anything. The usual way would be to pass the copy target to the function, like on heap

// allocate enough memory to hold the cipher text
// +1 for the null terminator
string ciphertext = malloc((strlen(plaintext) + 1) * sizeof(char));

plainToCipher(plaintext, ciphertext, key);
// next print the ciphertext

// and finally free the memory
free(ciphertext);

or here even simpler on stack

// allocate enough memory to hold the cipher text
char ciphertext[strlen(plaintext) + 1];

plainToCipher(plaintext, ciphertext, key);
// next print the ciphertext

// no need to free anything

In theory, you could do the malloc in the function, and free in the calling code, but that's not exactly easy to read.

In any case, don't forget the null terminator '\0' at the end of the string.

And your do..while loop (why not for or while?) looks pretty infinite. But that part is for another question.

0

Initialize strings with

char* <name> = <value>;
1
  • Initialize strings with char *<name> = "value"; It is a bit more advanced version for declaring strings in C as it is super pure form which includes knowledge of pointers from week 4 For week 2 students it is not recommended. Jul 18 '20 at 15:33
0

The compiler is actually giving you a hint as how to prevent this warning:

enter image description here

Just set it like it says at the very top where you declared the variable

string cipher = NULL;

or try setting it on an empty string (not sure if this will work in C as I'm new to it)

string cipher = "";

You must log in to answer this question.

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