I am having a little bit of trouble understanding the use of pointers. Specifically, I am confused about the following line of code:
char* s = "my String";
I have two questions:
Is this code even legitimate? From watching some of the Harvard CS 50 videos, I would think that it is.
If the answer to (1) is yes, then I am quite confused. I thought the meaning of the statement: "char* s" is that you want to create a new variable called s that is of type char*. This means that s is a pointer to some char variable (and at this point, we don't even know what this char variable is). If this is the case, then the right hand side of the above line of code should be an address in memory, and not a string.
I would be more comfortable with something like:
char s[10] = "my string"; //10 because including extra space for null 0
char* AddressOfs = &s;
EDIT/UPDATE: Thanks for all the great answers. David K's answer has made things much clearer (I like the step-by-step structure), but I am still a bit confused in some respects.
In step 1 of David K's answer, he said that
It will reserve 10 bytes of memory somewhere.
But it has to reserve more than just 10 bytes, right? We need 10 bytes for the contents of the string plus 4 bytes for the contents of the address in memory.
Do you agree with the following: So if we stick with the "variables-as-containers" analogy, the line
char* s = "my string";
reserves 14 bytes of storage (10 for the contents of the string and 4 for the address of the contents of the string), but there is only one "container". This container is named s and holds the 4 bytes. The 10 bytes that hold the contents of the string are "container-less", i.e. these 10 bytes are allocated somewhere in memory, but there is no label that we can associate with these 10 bytes. (I'm not saying we have no way of accessing these 10 bytes. I'm just saying that there is no formal variable label that is being applied to these 10 bytes.)
printf("%c", 1["Hello"])
. You might be surprised. The swap1
and the string literal and try again. Note: That is just to make you think - do not use this in your code. You will find the answer here already, so please do not add a new one.char s[] = "my string";
ands
is right-sized to 10. 2)&s
is the address of a pointer to an array of 10char
- not the same type aschar *
.s
is a variable, as such it needs memory (as any normalint
would). It happens that it points to an address, but thats just a detail. No additional space is required, if you lose that address, its lost for good, no one keeps track of it. Then,s
is a variable (that consumes 4 bytes), that points to a piece of memory that has 10 bytes. Hope this clarifies a bit.