0

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]);
7
  • 6
    Well, word[x] has a character type and not pointer... So your format specifiers are not matching. Why do you think it should work? Commented Mar 3, 2020 at 20:38
  • 4
    Use &word[x] to get the address for printing. Commented Mar 3, 2020 at 20:39
  • 5
    unrelated: prefer printf("........\n"); as opposed to printf("\n...");. Commented Mar 3, 2020 at 20:39
  • You would have to add the & to get the pointer as using [] for arrays automatically dereferences the value Commented Mar 3, 2020 at 20:39
  • When you say printf("\nAddress of word[1]: %p", word[1]); doesn't work, do you mean doesn't work as expected? You're not having a compilation error, are you? Commented Mar 3, 2020 at 20:40

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.