Deepak
Deepak

Reputation: 3

Pointers are used to store address, but in strings like char *ptr = "abc" then if you print 'ptr' why it is printed abc instead of address

Pointers are used for mainly to store the address of other variable like below code,

char a='A',*p;
p=&a;
printf("p: %p *p: %c p: %c\n",p,*p,p);

output: p: 0x7ffc81b8d9ef *p: A p: �

1.From above output if we want to print 'p' value then it's getting garbage value.

In strings

char *p ="A";
printf("p: %p *p: %c p: %s\n",p,*p,p);

output:p: 0x55ce091de714 *p: A p: A

2.From above output if we want to print 'p' value then it's print as A.

From 1 & 2 'p' is used for store the address only but in 2nd case why it is printing total string and why it is unable to print value in 1st case.

How can we ensure this ?

Upvotes: 0

Views: 173

Answers (1)

John Bode
John Bode

Reputation: 123448

1.From above output if we want to print 'p' value then it's getting garbage value.

The %c conversion specifier expects its argument to have type char. p has type char * and stores the address of a. Because of this type mismatch, the behavior is undefined and the output could quite literally be anything. One possibility is that printf is trying to interpret the first byte of p as a char, but the value is likely outside the range of printable characters in the basic character set, so you get a glyph in whatever extended character set is used by the system.

2.From above output if we want to print 'p' value then it's print as A.

The %s conversion specifier expects its argument to have type char * and to point to the first character in a string. It then prints each successive character of that string until it sees the string terminator. If your string was "ABC", then the output would be p: <some address> *p: A p: ABC.

Upvotes: 1

Related Questions