S
Seebs
Why?
Because they are all the same thing. All pointers to the same type of
thing are the same kind of object.
It's like ints. In a given implementation, "int" always means the same
sized thing, whether the value it holds is 1 or 60000..
Possibly my understanding is not very clear, that's why I am asking
here.
Okay.
This example is trivial.
It is less trivial to understand why, if I declare
const char *example[] = {
"hello", "a"
};
then I find that sizeof(example[0]) is 5 and sizeof(example[1]) is
still 5.
I don't believe this.
I don't believe this because I have never heard of a machine with
a 5-byte pointer type.
Now, if you were getting *4* all the time, that would make sense, because
on many machines, pointers are 4 bytes.
(Also, I should point out: The array denoted by "hello" is actually *6*
bytes, because it's terminated.)
Why?
Again, it didn't actually happen. So try running ACTUAL code and
looking at the results.
This result lead me to think that in this case too the memory is
h e l l o \0 a \0 \0 \0 \0 \0
exactly the same of your example.
No.
In other words, the compiler has to assign to the pointer the maximum
size, correct?
No.
POINTERS ARE OF A FIXED SIZE.
Okay, here's the deal. Imagine that your computer has a billion bytes
of memory. When your program is running, all those strings are loaded
in memory somewhere. So we just start counting from zero and numbering
all the memory.
So say your program has these strings starting at 0x100000.
0x100000 h
0x100001 e
0x100002 l
0x100003 l
0x100004 o
0x100005 \0
0x100006 a
0x100007 \0
Now, what's in the array?
char *str[2] = { "hello", "a" };
is exactly like
char *str[2] = { 0x100000, 0x100006 };
And because 0x100000 and 0x100006 are the same type of thing, and they are
probably both represented as 4 bytes, sizeof(str[0]) == 4, and sizeof(str[1])
== 4.
Because you're not getting the sizes of the things-pointed-to, but of the
pointers.
Disclaimer: The above is grossly oversimplified. The size of a pointer
could be 1, or 4, or 8, or 2, or 6, or 5, or whatever else; however, all
pointer-to-char will be the same size on a given implementation. In
most modern systems, the memory addresses you're using are "virtual",
meaning that two different programs can have different objects that they
see as being at 0x100000. There's a lot of oversimplification here.
The point is, when you have a string literal, the string contents are stored
somewhere, but the actual object created in the code is an *address*, which
is sort of like a special kind of number, and the *addresses* of things
of the same type are always the same size. (On some systems, pointers to
different types of objects could be different sizes.)
-s