This question already has answers here:
Closed 5 years ago.
Belows are simple code that compares size of array itself and size of pointer to array.
#include <stdio.h>
int main(){
int kkarray[100]= {1,0,};
int (*kkpointer) = kkarray;
printf("size of array using array itself : %ld \n" , sizeof(kkarray));
printf("size of array using pointer to array : %ld \n" , sizeof(kkpointer));
}
but the result is,
400
8
I could understand that the first value is 400, but second one,, i think that it also should be 400 because as i assigned a pointer that points to array, kkpointer, it kinda acts like name of array, which is const address value. For example, i can get the first value of array using kkpointer[0].
I want to know why i got '8' instead of 400.
I don't think the '8' is the size of address itself.
please let me know. Thanks
The size of any pointer is always 8
on your platform, so it's platform dependent.
The sizeof
operator doesn't care where the pointer is pointing to, it gives the size of the pointer, in the first case it just gives the size of the array, and that is not the same.
This is a quote from § 6.5.3.4, ¶ 2 N1570 draft
The sizeof operator yields the size (in bytes) of its operand, which may be an
expression or the parenthesized name of a type. The size is determined from the type of
the operand. The result is an integer. If the type of the operand is a variable length array
type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an
integer constant
and § 6.5.3.4, ¶ 4
When sizeof is applied to an operand that has type char, unsigned char, or
signed char, (or a qualified version thereof) the result is 1. When applied to an
operand that has array type, the result is the total number of bytes in the array.103) When
applied to an operand that has structure or union type, the result is the total number of
bytes in such an object, including internal and trailing padding
so as you can see, when applied to the array, it gives the total bytes. But if you pass a pointer, then the result will be the size of it's type.