Converting lowercase and lowercase letters and printing them

When I convert and print it in the same loop, I get the result plus the garbage I don't know where it came from. 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, then 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

      

+3


source to share


2 answers


You have undefined behavior. The problem is with your loop: it looks for \ 0 and there are none. So, with great luck, you see a problem that is worse than working, which you think works fine, because it looks good, as if it is normal, but it is just a problem waiting for it to happen.

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



Hello

+5


source


This array is not null terminated, you must insert the terminator yourself if you intend to use this loop



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

      

+4


source







All Articles