Reputation: 7844
When I execute the following code:
int main()
{
char **temp;
printf("Size of **temp %d", sizeof(**temp));
printf("Size of *temp %d", sizeof(*temp));
printf("Size of temp %d", sizeof(temp));
return 0;
}
I get:
Size of **temp 1
Size of *temp 8
Size of temp 8
What I don't understand is how does a char
pointer have a size of 8
? Is it machine independent?
Upvotes: 3
Views: 1961
Reputation: 49
size of pointer will depend on your machine(check your machine type).If your machine is 64 bit then pointer size is 8 bytes and for 32 bit machine pointer size is 4 bytes.
pointer size will be same irrespective of type of the pointer that pointer variable points to. pointer type is more useful for pointer arithmetic, don't be confused with its size when using sizeof operator
Upvotes: 1
Reputation: 101
If you are running MS Visual Studio on a 64 bit machine, you can change the Solution platform from win32 to x64 to see the size of the pointer growing from 4 to 8 bytes with this code.
Upvotes: 2
Reputation: 1206
Size of **temp 1
Size of *temp 8
Size of temp 8
it's showing the right answer. Why?
Because
Size of **temp 1--->> pointing to char.
Size of *temp 8----->>pointing pointer to char.
Size of temp 8---->>>>pointing pointer to pointer to char.
and you are using 64 bit compiler if you will run this code on 32 bit compiler it will give you
Size of **temp 1
Size of *temp 4
Size of temp 4
Upvotes: 0
Reputation: 7630
sizeof operator is resolved by the compiler at COMPILE TIME. No actual deference-ing occur at runtime. What is return by the size of operator is the size of the type. so
sizeof(*(char *)0) is 1
If the target platform has 64 bit pointers, then sizeof(temp) would be 8. If the target platform has 128 bit pointers, then sizeof(temp) would be 16.
"target" doesn't mean it is the platform you compile on, because you can cross-compile.
Upvotes: 1
Reputation: 612954
The size of a pointer is machine dependent.
What I don't understand is how does a char pointer have a size of 8
A char pointer, i.e. a char*
variable does have a size of 8, on your system. In your code sizeof(*temp)
gives the size of a char pointer, and it is 8. The reason sizeof(**temp)
is 1 is that **temp
is char
and sizeof(char)
is 1 by definition.
Upvotes: 1
Reputation: 64682
In the original question you weren't calling sizeof
.
duskwuff fixed that for you.
The output produced was:
Size of **temp 1
Size of *temp 8
Size of temp 8
Reason:
On a 64-bit architecture, pointers are 8-bytes (regardless of what they point to)
**temp is of type char ==> 1 byte
*temp is of type pointer-to-char ==> 8 bytes
temp is of type pointer-to-pointer-to-char ==> 8 bytes
Upvotes: 6
Reputation: 182639
Is sizeof char ** pointer dependent on the architecture of machine
More than machine dependent, it's compiler-dependent. The only size you can always rely on to be the same is sizeof(char) == 1
.
Upvotes: 6