char * enigma

Hello :)
I'm trying to understand how char* works. I searched all the day but I couldn't find a good explanation...
When creating a pointer you initialize it with an address,for example:
1
2
int a;
int *p=&a;

So the side left the equal sign is an address.
In this case:
char *p="troll";
The left side doesn't look like an address...
Can someone explain me how this work ?
First, let's make it valid C++,
const char *p="troll";
There are several concepts involved here:
1. A string literal "troll" defines an anonymous static array of const char, so this line is equivalent to
1
2
static const char _unique_name_[6] = {'t', 'r', 'o', 'l', 'l', '\0'};
const char *p = _unique_name_;

2. when an array is used in context where arrays aren't allowed, but pointers are, a pointer to the array's first element is constructed, so this line is equivalent to
1
2
static const char _unique_name_[6] = {'t', 'r', 'o', 'l', 'l', '\0'};
const char *p = &_unique_name_[0];

there you go, you're storing the address of the character 't' in your pointer p.
Last edited on
Topic archived. No new replies allowed.