简体   繁体   中英

Why do I get an error when my Caesar cipher program executes?

I am working on a Caesar cipher program. Currently i am trying to encrypt a message. I am writing a function to complete this task. The compiler executes the code without any errors, but the final output of the code, which it is supposed to display the encrypted message, it produces, The encrypted message is:

����

Why might this be so?? My faulty code is below. Any form of help would be appreciated. Thank you in advance.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

The code shouldn't even compile. (Type mismatch between char(*)(char*, int) and char .)

 return (encrypt_rot); 

returns the address of the Function encrypt_rot . Maybe you wanted to write return a; . But then you should know, that you should not return the address of a local variable ( a in this case) from a function because the variable is gone once the function returns to its caller and the returned pointer is no longer valid. Also the return type of encrypt_rot which is char doesn't match the type of a which is char[100] or, in this case with return a; it's char * .

I'd suggest you modify the parameter x in place:

void encrypt_rot(char x[100], int y)
{
    for (size_t i = 0; i < 100 && x[i] != '\0'; ++i)
    {
        x[i] += y;
        if (x[i] > 'z')
            x[i] -= 26;
    }
}

Btw, you should think of better names for your variables.

 scanf(" %[^\\n]s", message); 

You should never, never, really never use the %s format specifier without specifying a SIZE to prevent buffer overflow:

scanf(" %99[^\n]", message);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM