简体   繁体   中英

Printing char array in C

void main(){
char s[10];

s[1]='a';
s[6]='4';
for(int i=0;i<10;i++)
    printf("%c",s[i]);
}

I have this simple program. It gives the following output:

@aO   4

If I change the above code to:

void main(){
char s[10];

s[1]='a';
s[6]='4';
for(int i=0;i<10;i++)
    printf("%c",s[i]);

printf("\n");

for(int i=0;i<10;i++)
    printf("%c",s[i]);

}

Output changes to:

@a@ 4
@a@ 4

There are actually 2 cubes containing 4 numbers (1 number in each quadrant of the cube) between 'a' and the '@' after a but for some reason they are not showing.Please try the above codes in code blocks if I do not make sense to you.

I was expecting the output to be a 4 by the first code.Why is it not so? Also, why did the output change when I added more code? I was expecting the output to be:

a    4
a    4

The problem is that you didn't initialise your array. In order to get that output you can do it in this way:

char s[10];

for(int i=0;i<10;i++)
{
    s[i] = ' ';
}
s[1]='a';
s[6]='4';
for(int i=0;i<10;i++)
    printf("%c",s[i]);

Here

char s[10]; /* uninitialized array */ 

character array s is not initialized & default s elements contain garbage data as it has automatic storage duration and you have assigned values to only s[1] and s[6] .

Hence array elements except s[1] and s[6] contains garbage data & printing their value is not guaranteed to be same Every time as you have shown.

To avoid this you can initialize array like this

char s[10] = ""; /* initialize all array elements  with 0 */

while declaring itself.

You got to understand behavior behind your program. So when you load your program it is given N bytes in memory and that N bytes gets reused many times and not erased. So in first instance your program have loaded some data into spot where s[0] would later reside, where as in second something was loaded where s[2] as well. That is why you are getting different output in these 2 cases.

So to sum it up: Your array is not initiated to 0 or unless you do it your self, it is given memory that have been previously used by the same program. To do it as it was pointed before you have to do this:

char s[10] = "          ";
....

One more thing I see is you were not expecting space before a , in C/C++/Java array indexes start at 0 . So if you do:

char s[4];

s[1] = 'a';
s[2] = 'b';
s[3] = '\0';

print ("%s", s);

you would probably get:

@ab

@ comes up because there was nothing written by you as programmer in memory spot where s[0] resides.

Note that every time you have string in C you have to terminate it with '\\0' character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM