Weird characters in encrpytion function

I have been tasked to do a ROT13 encryption function and everything looks fine except that it outputs 52 characters even when I have specified 26 characters in the array. Can anyone help me figure out what's the problem?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

#include <stdio.h>
#include <ctype.h>
void rotate13(char s[], int size, char t[]);
int main(void)
{
char s[27]="abcdefghijklmnopqrstuvwxyz";
char t[26]={0};
rotate13(s, 26, t);
printf("%s\n", t);
return 0;
}


void rotate13(char s[], int size, char t[])
{
int i;
for(i=0;i<size;i++)
{	if (isalpha(s[i]) && s[i] !='\0')
		{	if (islower(s[i]) && s[i] > 'm' && s[i] <= 'z')
			{t[i] = (s[i]-13);}
			if (islower(s[i]) && s[i] <= 'm' && s[i] >= 'a')
			{t[i] = (s[i]+13);}
			if (isupper(s[i]) && s[i] > 'M' && s[i] <= 'Z')
			{t[i] = (s[i]-13);}
			if (isupper(s[i]) && s[i] <= 'M' && s[i] >= 'A')
			{t[i] = (s[i]+13);}
		}
	else if (isalpha(s[i]) == '\0')
		break;

}
}
printf will output an array of characters until it finds the character with the numerical value of zero. That is how printf knows it has reached the end of the string.

If you build a char array for use with printf, you must ensure you put a zero value at the end.

That works, but I'm still puzzled. If what you said is true then why did the codes below work? Isn't the last character for the str the NULL character?

1
2
3
4
5
6
7
8
9

#include <stdio.h>
int main(void)
{
char str[] ="Blahblah";
printf("%s\n", str);
return 0;
}



When you create a char array from a string literal, such as

char str[] ="Blahblah";

the array of characters that is created has a zero value put on the end. The NULL character is the character with the value zero.
Last edited on
Oh, thanks for clearing that up.
Topic archived. No new replies allowed.