1

I am trying to understand one pointer example in the o'reilly "Practical C" book regarding "const pointers".

const char *answer_ptr = "Forty-Two";

answer_ptr = "Fifty-One"; /* Legal because the pointer is a var and not constant
*answer_ptr = 'X'; /* Illegal because defined as constant.

What I don't understand is, what exactly is the "Forty-One"? Where is it stored, and what can I used it for?

If I try it out in CodeBlocks:

const char *answer_ptr = "Forty-One";
printf("Pointer: %s, Content: %c, Address %p.\n", answer_ptr, *answer_ptr, &answer_ptr);

answer_ptr = "Twenty-Two";
printf("Pointer: %s, Content: %c, Address %p.\n", answer_ptr, *answer_ptr, &answer_ptr);

The output is:

Pointer: Forty-One, Content: F, Address 0060FF0C.
Pointer: Twenty-Two, Content: T, Address 0060FF0C.

So it seems I can change the content of the variable the pointer is pointing to, even that I defined it as "const".

Is my understanding correct or do I miss here an important point?

To be honest I am very confused since answer_ptr and *answer_ptr seem to be the same...

Thank you guys for your help! Cheers, Styx

roschach
  • 8,390
  • 14
  • 74
  • 124
Styx1337
  • 37
  • 6
  • answer_ptr is pointer(it contains address), *answer_ptr is value stored in memory answer_ptr points to – purec May 27 '18 at 09:50
  • https://stackoverflow.com/questions/21476869/constant-pointer-vs-pointer-to-constant?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – purec May 27 '18 at 09:53
  • *answer_ptr is not the same. It is 'F', then 'T'. Very good demonstration. – purec May 27 '18 at 09:55
  • @purec 2 questions: - but why does 'printf' print then a string if i write answer_ptr? - and why can I asign a string to an address(pointer)? – Styx1337 May 30 '18 at 03:29
  • You should not use & before pointer name in printf. – purec May 30 '18 at 08:48
  • In our case read-only is memory not pointer. You can't do this for example "const1.c:9:2: error: assignment of read-only location ‘*(answer_ptr + 2u)’ answer_ptr[2] = 'a';" – purec May 30 '18 at 08:56

0 Answers0