Search code examples
cpointersdereference

Why printf( "%s" , ptr ) is able to dereference a void*?


When we talk about dereference, is it necessary that * should be used in it? If we access the referent of the pointer in some other way, can it be considered as dereferencing a pointer or not, like:

char *ptr = "abc" ;
printf( "%c" , *ptr ); // Here pointer is dereferenced.
printf( "%s" , ptr );  // What about this one?

That is the first part of my question.

Now if printf( "%s" , ptr ) is an example of dereferencing then kindly answer the following part of my question too.

K&R says

a "pointer to void" is used to hold any type of pointer but cannot be dereferenced itself

Hence,

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

Does not compile, complier gives error

In function ‘main’: warning: dereferencing ‘void *’ pointer error: invalid use of void expression

But if we use

char *a = "c" ;
char *p = a ;
void *k = a;
printf( "\n%c\n" , *p );
printf( "\n%s\n" , k );

It compiles and works. Which means void pointer can be dereferenced - we have got the object pointer is referring to.
If that's the case then what does K&R above mentioned quote means in this context?

Thanks for your time.


Solution

  • No. what you have is "undefined behaviour" - the C language standard does not say what should happen. In your case, it "works", but for another user/compiler/platform it might not. Your statement:

    printf( "\n%s\n" , k );
    

    is equivalent to:

    int k = 42;
    printf( "\n%s\n" , k );
    

    and is equally undefined.