I have a function (called encrypt) that will return a string (called ciphertext). Inside this function, I created an array char[] (called cptxt_arr) and after running a loop and creating the ciphertext from the plaintext (got it from the user), I stored each letter inside the char[], then I assigned the char[] to the string and returned the string.
Here's my question: In the main(void) function, how come, when I print the encrypt function as a string (%s) I don't get anything from the CLI, but if I print the same function as char (%c) I do get the letters?
PS: From what I've read, I know I can't return arrays in C, which is why I'm assigning the char[] to a string variable and returning that.
I just want to know why is this happening because If I print the string ciphertext inside the encrypt function it works meaning that the code works fine.
NOTE: For the sake of the question, use positive integers for the "key" variable. I cleaned a bit the code, so the important part could be seen more easily.
Here's the code:
#include <cs50.h> #include <stdio.h> #include <string.h> string encrypt(string plaintext, int key); int main(void) { int key; string plaintext; // Get the key. key = get_int("Key: "); // Get plaintext from the user. plaintext = get_string("plaintext: "); // Print encrypted text. printf("ciphertext: %s\n", encrypt(plaintext, key)); // Same but with the formatted char (%c). // printf("ciphertext: %c\n", encrypt(plaintext, key)[0]); } // Encrypt text. string encrypt(string plaintext, int key) { // Get plaintext length. int length = strlen(plaintext); char cptxt_arr[length]; string ciphertext; for (int i = 0; i < length; i++) { if (plaintext[i] >= 'A' && plaintext[i] <= 'Z') { cptxt_arr[i] = ((plaintext[i]) + key); } else if (plaintext[i] >= 'a' && plaintext[i] <= 'z') { cptxt_arr[i] = ((plaintext[i]) + key); } } // Assign cptxt_arr[] to string and returning it. ciphertext = cptxt_arr; return ciphertext; } I have (I don't if it could matter) created a variable in the main(void) function and assigned the encrypt function to it, which doesn't work either.
malloc()the array inside the function, or (better!) 2) allocate a char[] buffer OUTSIDE, and pass it as an argument INTO the function.stringandchar*interchangeably in cs50.