arniem
arniem

Reputation: 145

Pointers and string literals in C

Suppose, in C language I have the following code, where pointer variable "word" points to a string literal.

const char * word = "HELLO";

Why does this works -

printf("\nword[1]:  '%c'", word[1]);
printf("\nword[2]:  '%c'", word[2]);

and this doesn't ?

printf("\nAddress of word[1]:  %p", word[1]);
printf("\nAddress of word[2]:  %p", word[2]);

Upvotes: 0

Views: 87

Answers (1)

0___________
0___________

Reputation: 68089

because the latter is char not pointer. word[1] is the same as *(word + 1) and you just dereference the char pointer. The result is char

you need to:

printf("\nAddress of word[1]:  %p", (void *)&word[1]);
printf("\nAddress of word[2]:  %p", (void *)&word[2]);

or

printf("\nAddress of word[1]:  %p", (void *)(word + 1));
printf("\nAddress of word[2]:  %p", (void *)(word + 2));

Upvotes: 3

Related Questions