Hi I am new to C but not to programming(Only have experience in high-level languages like Python and JS).
In my CS assignment I have to implement a function that decodes an encrypted string.(The encryption used is atbash)
I want to give the decode-function a encoded string and receive a decoded string. I tested my function by printing out every decoded character of the string and it worked.
However I am having issues implementing the original task of the function (encoded str -> decoded str)
Here is my code:
#include <stdio.h> #include <string.h> /*******************/ // atbash decoding function // recieves an atbash string and returns a decoded string. char *decode(char *str){ int i = 0; char decodedString[1000]; strcpy(decodedString, "\n"); while(str[i] != '\0') { if(!((str[i] >= 0 && str[i] < 65)||(str[i] > 90 && str[i] < 97)||(str[i] > 122 && str[i] <=127))){ if(str[i] >= 'A' && str[i] <= 'Z'){ char upperCaseLetter = 'Z'+'A'-str[i]; strcat(decodedString, &upperCaseLetter); } if(str[i] >= 'a' && str[i] <= 'z'){ char lowerCaseLetter = 'z'+'a'-str[i]; strcat(decodedString, &lowerCaseLetter); } } if(((str[i] >= 0&& str[i] < 65)||(str[i] > 90 && str[i] < 97)||(str[i] > 122 && str[i] <= 127))){ char notALetter = str[i]; strcat(decodedString, ¬ALetter); } i++; } printf("%s\n", decodedString); // Debug: Checking what I would receive as a return, expected "Hello World!", got binaries return decodedString; } int main(){ char *message = "Svool Dliow!"; printf("This is the decode String:\n%s",(decode(message))); //Expected return of "This is the decode String:\nHello World!", received "This is the decode String:\n" instead return 0; } Issues:
(1)
I receive in the debug comment some binaries, instead of a string ("Hello World!").
(2)
I don't understand why printf("\n%s", (decoded(message))); doesn't print the callback of function decode ._.
Thanks in advance!
Edit:
Issue (2) was solved thanks to paulsm4
Edit2:
Issue (1) was solved thanks to dbush.
char decodedString[1000];INSIDE of your function. That storage (stack storage) becomes INVALID once the function exits.decodedStringindecode) will be released when the call to the function ends. You are referencing de-allocated memory.strcatshould be a pointer to a null-terminated string, not a pointer to a single character.