Search code examples
c++encryptioncaesar-cipherchar-pointer

Caesar Cipher using char * ? c++


So i am trying to use the Ceasar Cipher with char *'s, I've written a simple function out like this:

char * Encrypt(char * s, int k)
{
    char * c = s;

    for(int i = 0; i < strlen(s); i++)
       c[i] += k;

    return c;
} 

that seems to look like it should work but it doesn't. It throws an error when running program.

Here is an example of how i call this function:

int main()
{
    cout << Encrypt("hello", 2) << endl;
    system("pause");
    return 0;
}

And before you say "why not just use string?", well the answer is I'm writing C++ on a certain SDK that causes compiler errors when using string. Ok but yeah, any form of help will greatly be appreciated, thanks!


Solution

  • String literals like "Hello" are read only. If you try to modify such a string you will have undefined behavior.

    In C++ string literals are actually arrays of constant characters.

    Using char* to access a string literal should have your compiler to scream a warning at you. If not you need to turn up your warning level or enable more warnings.

    If you're really programming in C++ I suggest you learn about std::string and find a good beginners book to read.