Mor Haham
Mor Haham

Reputation: 65

Converting lowercase to uppercase letters and printing them

When I convert and print it in the same loop i get the result plus a garbage that I don't know from where it came. Example:

Input:

char array_ch[]={'A','B','C','D','E'};
int i=0;
for(i;array_ch[i]!='\0';i++){
  array_ch[i]=array_ch[i]+32;
  printf("%c",array_ch[i]);
}

Output:

abcde`H��A���/��u�$(!

And if I print it in another loop its ok:

Input:

char array_ch[]={'A','B','C','D','E'};
int i=0;
for(i;array_ch[i]!='\0';i++){
  array_ch[i]=array_ch[i]+32;
}


for(i=0;array_ch[i]!='\0';i++){
  printf("%c",array_ch[i]);
}
printf("\n");

Output:

abcde

Upvotes: 3

Views: 118

Answers (2)

Friedrich
Friedrich

Reputation: 6006

You have undefined behavior. The problem is your loop: it looks for a \0 and there is none. So with sheer luck you see the problem it's worse with the run you think works ok, because well it looks as if it's ok but it's just a problem waiting to be happen.

So write:char array_ch[]={'A','B','C','D','E', '\0'}; and you should be fine

Regards

Upvotes: 5

Marco A.
Marco A.

Reputation: 43662

That array isn't null-terminated, you should insert a terminator yourself if you intend to use that loop

char array_ch[] = { 'A', 'B', 'C', 'D', 'E', '\0' };

Upvotes: 4

Related Questions