APan
APan

Reputation: 366

Weird behavior of pointer

When I compile the given code it doesn't produce any error or warnings. My question here is shouldn't the compiler produce error when compiling the following line *err = "Error message"; because we are dereferencing a pointer to pointer to constant char and assigning a string to it.

Is it allowable to assign anything inside a pointer anything other than address and exactly what is happening in this given scenario?

#include <stdio.h>

void set_error(const char**);

int main(int argc, const char* argv[])
{
    const char* err;
    set_error(&err);
    printf("%s",err);
    return 0;
}


void set_error(const char** err1) 
{
     *err1 = "Error message";
}

Upvotes: 1

Views: 140

Answers (3)

Slava
Slava

Reputation: 44268

Is it allowable to assign anything inside a pointer anything other than address and exactly what is happening in this given scenario?

You can assign pointer to a pointer. You think about pointer as an address, that's fine to understand concept, but do not mix it with data type. Data type is a pointer, not address. For example to assign address in memory to a pointer you need to cast it to a pointer:

char *pointer = reinterpret_cast<char *>( 0xA000000 );

You may ask how this would compile?

int array[10];
int *ptr = array;

That comes from C - array can be implicitly converted to a pointer to the first element. So it is pointer to pointer assignment again. Now about string literal with double quotes. It is an array as well:

const char str[] = "str";
const char str[] = { 's', 't', 'r', '\0' }; 

These 2 statements are pretty much the same. And as array can be implicitly converted to pointer to the first element it is fine to assign it to const char *

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254701

const char** err1

That's a pointer to a non-constant pointer to a constant object. Dereferencing it gives a non-constant pointer (to a constant object), which can be assigned to.

To prevent assigning to the const char*, that would also have to be const:

const char * const * err1

Upvotes: 9

Collin
Collin

Reputation: 12287

"Error message" is not a std::string. It's a const char[]. All string literals in C++ are const char[]. In C, they're char[].

Upvotes: 4

Related Questions