char * ch = "where does this pointer store all these characters?"

i am having trouble understanding a char *. how does it handle the, what seems to be, limitless string literals it can point to?

for example, lets consider an int *;

int x = 5; // create an int variable and initialize it.
int * p_int; // create a pointer to an integer.
p_int = &x; // assign the pointer to the int variable.

this int * must be assigned an address of another int variable, as shown above. what i mean is that you cannot create the pointer and assign it the 5 value.

int * a_int = 5; // this will not even compile.

char * ch_p = "but this will compile!" // so how does this work?
// all these character literals take up memory space. where are they located?
// this does not make sense because i do not understand what the pointer points to.

i mean, you can also do this;
char ch = 'P'; // create a char variable and initialize it.
char * u = &ch; // create the char pointer and give it an address of ch.
cout << *u; // dereference u to display P.
// see, this way makes sense because the ch variable was created first, and the pointer points to it.
char * ch_p = "but this will compile!" // so how does this work?

That does not work, it is ill-formed (cannot be compiled), unless you're using an older compiler from when this was allowed (but deprecated). The proper code is

const char * ch_p = "but this will compile!"

// all these character literals take up memory space. where are they located?
// this does not make sense because i do not understand what the pointer points to.

The string literal "but this will compile!" declares an unnamed array of const char with static duration. It is as if you wrote
1
2
static const char foo[] = {'b', 'u', 't', ' ', ..... 'e', '!', '\0'};
const char* ch_p = &foo[0];
thanks for the quick reply.

i am using newest version of codeblocks compiler. it does compile.
i assume nameless arrays, variables, and entities are something programmers should avoid.? when something is typecasted it also generates a nameless instantiation.
A pointer points to ONE THING. There may be other things AFTER that one thing, but the point just points to the first one. It doesn't "hold" what is points to, it holds a memory address.

http://www.cplusplus.com/doc/tutorial/pointers/
Last edited on
Topic archived. No new replies allowed.