Reputation: 6492
I was reading more about arrays vs pointers in C and wrote the following program.
#include <stdio.h>
int arr[10] = { } ;
typedef int (*type)[10] ;
int main()
{
type val = &arr ;
printf("Size is %lu\n", sizeof(val)) ;
printf("Size of int is %lu\n", sizeof(int)) ;
}
If, I execute this program, then sizeof(val)
is given to be 8 and sizeof(int)
is given to be 4.
If val
is a pointer to the array with 10 elements, shouldn't it's size be 40. Why is the sizeof(val)
8 ?
Upvotes: 2
Views: 94
Reputation: 310980
First of all this initialization of an array
int arr[10] = { } ;
is invalid in C. You may not use emplty braces in C (in C++ they are allowed). You have to write
int arr[10] = { 0 } ;
In C the corresponding initializer is defined the following way
initializer:
{ initializer-list }
{ initializer-list , }
while in C++
braced-init-list:
{ initializer-list ,opt }
{ }
As for this statement
printf("Size is %lu\n", sizeof(val)) ;
then val
is a pointer because it has type type
defined like
typedef int (*type)[10] ;
Change this statement to
printf( "Size is %zu\n", sizeof( *val ) );
if you want to get the size of the object (that is of the array) pointed to by the pointer.
Upvotes: 3
Reputation: 134326
If val is a pointer to the array...
Yes, it is, and sizeof(val)
produces the size for the "pointer to the array", not the array itself.
...shouldn't it's size be 40.?
No, sizeof(val)
calculates the size of the operand, the "pointer" here. In your platform, the size of a pointer seems to be 64 bits, i.e., 8 bytes. So, it gives 8
.
Also, as I mentioned, use %zu
to print size_t
, the type produced by sizeof
operator.
Upvotes: 3
Reputation: 5619
Most probably you are in a 64 bit
PC where memory address need 64 bits
or 8 byte
space for representation.
Now the pointer
actually holds the memory address, whereas it may hold an address of int
or maybe an address of int[]
, doesn't matter.
So, when you execute,
printf("Size is %lu\n", sizeof(val)) ;
it shows 8
as because the pointer holds address which need 64 bits
space.
And
printf("Size of int is %lu\n", sizeof(int)) ;
this line just print the size of int
which is 4
bytes.
Upvotes: 0
Reputation: 148
val
is pointer and its size is equivalent to address bus size of system.
so, sizeof(val)
or sizeof(anyPointer)
will give you 8
as output.
if you want 40
then try sizeof(arr)
.
Pointer to an array is simple pointer where you can write val++
while array name is constant pointer
you cannot write arr++
.
you can also check this link
Upvotes: 0
Reputation: 4859
A pointer
is a distinct data type and always has a fixd size. Think of a pointer as a sign that points to the actual data, and the sign always the same size - regardless if it points to a single character or a larger array.
Upvotes: 0
Reputation: 14543
sizeof returns the size of the pointer itself. In 64bit system it is 8 bytes. Pointers have no knowledge of the size of buffer they points to.
Upvotes: 0