Question about C string literals

If this array's name points to the first character of the string so that it knows where the string starts,
 
char array[3] = "my";

and this pointer to char variable points also to the beginning of the string.
 
char * p = "my";


My question is how do the char pointers know that what they are pointing to is the beginning of the string?

My question is how do the char pointers know that what they are pointing to is the beginning of the string?


They don't. You do.
@cire very constructive.

@OP, it's really just like the array. P will point to the first char, so dereferencing it will return 'm'. A pointer doesn't point to multiple chars (because char types only hold 1 char), so it's only natural that p ponts to the beginning char (implicitly) - just like your array does, because you never told array to point to the first char either, it just did - just like p does too.

You should use the string type though instead of C-style strings. :)
Last edited on
@cire very constructive.


It's very true. Whereas your explanation is inaccurate. Arrays don't point to things. They hold things.

A pointer is simply an address and a type. The type you give the pointer affects how the compiler treats the memory at the address the pointer contains and how pointer arithmetic works on it. The address you give the pointer affects where the pointer points to. The pointer doesn't know anything about anything.

It's a bit like sticking a tack into a map and asking how the tack knows it is stuck in a city.


Last edited on
Arrays don't point to things


everything ive read says arrays are like a constant pointer
@cire Sorry if I got a bit wrong. From where I learned (C++ Primer), whether we're talking about "technically this technically that" or not, I was taught arrays are implemented via pointers and when you declare an array, e.g. int MyArray[5], MyArray is actually a pointer that points to the first element. But yes you're right, they hold things. I see many mixed explanations on whether arrays are really pointers or not though.
Last edited on
everything ive read says arrays are like a constant pointer


If everything you're read says that defining a constant pointer allocates memory for elements of the type pointed to, I would suggest finding new reading material.
@cire
whats your resource?


EDIT:
heres something ive found

So, in summary: arrays are not pointers. In most contexts, array expressions are converted to pointer types.


which seems to make sense and agrees with what you were saying
Last edited on
Topic archived. No new replies allowed.