Manish Bharti
Manish Bharti

Reputation: 121

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

Upvotes: 2

Views: 1337

Answers (2)

llater
llater

Reputation: 29

In the first piece of code, you assign a char pointer p to an int value, then dereference the pointer and assign it to another integer. The dereference operator assigns the new value, the string containing 0, '0', to the memory address that was formerly occupied by ch+a.

In the second piece of code, the memory address at the pointer is assigned to an integer value of 0, and not the string '0'.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

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.

Upvotes: 2

Related Questions