I'm creating a Caesar cipher in C and I'm having an issue when displaying the encoded message. It works if the message consists of very few characters but as soon as the message exceeds a certain amount of characters the printf function begins to display unknown characters which I assume are junk bytes. Any ideas?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *concat(const char *s1, const char *s2)
{
/*
Remember to free allocated memory
*/
char *result;
if((result = malloc(strlen(s1)+strlen(s2)+1)) != NULL)
{
result[0] = '\0';
strcat(result, s1);
strcat(result, s2);
}
return result;
}
void encode(const char *alpha, const char *message)
{
char result[(sizeof(message) / sizeof(char))];
int x, y, z;
memset(result, '\0', sizeof(result));
for(x = 0; x < strlen(message); x++)
{
for(y = 0; y < 25; y++)
{
if(alpha[y] == message[x])
{
z = (y + 3);
if(z > 25)
{
z = z % 25;
}
result[x] = alpha[z];
}
}
}
printf("%s\n", result);
//return result;
}
int main()
{
char message[200];
char *result;
char array[26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
printf("Input your message:");
scanf("%s", &message);
encode(array, message);
}
Result: