Search code examples
carraysstringpointersnull-character

char array with pointer in c with %s


i have these two c programming code .They are identical except for one step and because of that their output is totally different please help me why is this happening

main()
{
char ch[10]="123456";
char *p;
int a;
scanf("%d",&a);
p=ch+a;
*p='0';
printf("%s",ch);
} 

output is 
nik@debian:~$ ./a.out 
4
123406

AND here is other one only have slight change at line [*p='0']

main()
{
char ch[10]="123456";
char *p;
int a;
scanf("%d",&a);
p=ch+a;
*p=0;        //only change is here rest is same
printf("%s",ch);
} 

and output is
nik@debian:~$ ./a.out 
4
1234

please hep me out why it is defferent it is because i am using %s in printf or for other thing which i have been missing


Solution

  • For ease of explanation, let's consider we're sticking to ASCII values all over.

    In the first case,

     *p='0';
    

    puts the ASCII value of '0' (decimal 48) into the memory pointed by p.

    In second case,

    *p = 0;
    

    puts the ASCII value 0 (decimal 0) itself into the memory pointed by p.

    Hence, in the first case, for the string supplied as the argument to %s the value at the given index (4) is 48, which makes it print the literal 0 and continue until it finds a null-terminator.

    Now, in the second case, because the ASCII 0 indicates the null-character at that given index, %s finds the end of the string and stops there.