I am trying to implement the rot13-algorithm in C. But since I am not very familiar with that language, I have some problems with my code right here.
Basically, I want to rotate every letter in args[] to 13 positions up. But this code seems to be pretty sluggish:
#include <stdio.h>
char[] rotate(char c[]) {
char single;
int i;
int alen = sizeof(c)/sizeof(c[0]);
char out[alen];
for(i=0;i<=alen;i+=1) {
if(c[i]>='a' && (c[i]+13)<='z'){
out[i] = c[i]+13;
}
}
return out;
}
int main(int argc, char *argv[]) {
printf("The given args will be rotated\n");
int i;
char rotated[sizeof(argv)/sizeof(argv[0])];
rotated = rotate(argv);
/* printing rotated[] later on */
return 0;
}
I know there a lot of holes here - could you show me how to fix this?
gdb
if you're on Linux) to step through your code, this help getting enlightend.gcc -Wall -Werror -pedantic -std=c99
(on linux) first :)char[] rotate(char c[]) { /* ... */ }
won't compile because functions can't return arrays. Also you can't assign to an array as a whole (like inrotated = rotate(argv);
). Maybe you can be more specific about you problem(s).sizeof
does not give you the number of elements in an array. It gives you the size (in bytes) of an object's type. When you receive an array as a parameter, you're really just receiving a pointer to an array. The logical size of the array could be any size; there is no way to tell. After all, it's all just bytes in memory. Therefore, all thatsizeof
can tell you is the size of the pointer. Also, your code that does the actual rotation is not ROT13. Consider what happens when c[i] is 'n' or "greater." You may also want to review how argc and argv work.