evaluate NULL to a pointer which a CONST pointer points to

G

G

Hi~
you guys.
I come across the code below:
/////////////////////////////////////////////////////////
#include <stdio.h>
void foo(const char **pp)
{
*pp=NULL;
//it works too
//*pp="Hello world!";
}

int main()
{
const char *p="hello";
foo(&p);
printf("%s",p);
return 0;
}
//////////////////////////////////////////////////////////
It was compiled successed without no warn or error.

Why can *pp change , though " const char **pp " meant it couldn't ?

Thank you ! :)
 
S

Sylvester Hesp

G said:
Well,I got the answer.

Then post the answer, so others can benefit as well! :)

So for the sake of completeness: you are allowed to change the pointer
because the 'pointer to const char' that the pointer points to is itself not
const. This may be a bit difficult to understand at first, so a few typedefs
would clear things up:

----------
typedef int the_type_pointed_to;

void foo(the_type_pointed_to * ptr)
{
*ptr = 3; // allowed
}

void foo(the_type_pointed_to const * ptr)
{
*ptr = 4; // not allowed, the_type_pointed_to is const.
}
----------

This is of course very obvious. Now, change the_type_pointed_to to be a char
const * rather than an int. You'll see that both overloads of foo are still
different - one works on a pointer to nonconst 'char const *', while the
other works on a pointer to _const_ 'char const *'. If you substitute
the_type_pointed_to with the actual type in the second definition, it would
read:
void foo(char const * const * ptr)

So it doesn't matter whether **ptr is const or when you want to change *ptr,
it matters whether *ptr itself is const!

- Sylvester
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top