c - Cesar Cipher out of bounds in Array -
guys found caesar cipher code in site.... when run showing segmentation fault in online compilers..but in c compiler tat i'm using showing processor fault... can pls point out wrong in code
#include <stdio.h> #include <stdlib.h> #include <string.h> #define caesar(x) rot(13, x) #define decaesar(x) rot(13, x) #define decrypt_rot(x, y) rot((26-x), y) void rot(int c, char *str) { int l = strlen(str); const char *alpha[2] = { "abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz"}; int i; (i = 0; < l; i++) { if (!isalpha(str[i])) continue; str[i] = alpha[isupper(str[i])][((int)(tolower(str[i])-'a')+c)%26]; } } int main() { char str[] = "this top secret text message!"; printf("original: %s\n", str); caesar(str); printf("encrypted: %s\n", str); decaesar(str); printf("decrypted: %s\n", str); return 0; }
your code correct except 1 detail, might confusing newbie.
it ok assume function isupper()
returns boolean value 1 or 0, if check documentation says a value different 0 (i.e., true) if indeed c uppercase alphabetic letter. 0 (i.e., false) otherwise. , fact isupper()
returning int , not _bool causing problem.
int isupper ( int c );
when returning true isupper()
might return non_zero value. in case returns 8
( specific bit-field ). same in yours.
all have cast return of isupper()
_bool
printf("%d %d" ,(_bool)isupper('a') , ((int)(tolower(str[i])-'a')+c)%26 ) ;
Comments
Post a Comment