-1

See below example in c:

    #include <stdio.h> 

    int main() 
    { 
        int arr[] = {1, 2 ,3}; 
        int *ptr = arr;

        printf("sizeof arr[] = %d ", sizeof(arr)); 
        printf("sizeof ptr = %d ", sizeof(ptr)); 

        return 0; 
    }

output: sizeof arr[] = 12 sizeof ptr = 4

Why sizeof on pointer "ptr" outputs 4 and on array variable "arr"(although "arr" is also being a pointer) outputs 12 ?

Vicky
  • 3
  • 2

3 Answers3

0

size of int is 4 bytes so the size of arr = sizeof(int) * 3 which is 12 as it contains 3 integers.

but ptr is a pointer to an array of integers. With a 32bit all the pointer will be size 4 bytes (32 bits)

Hope it helps

Nitheesh George
  • 1,357
  • 10
  • 13
0

Operator sizeof returns the size of an object's type. Your array has 3 integers so it is sizeof(int)*3. A pointer size in bytes is platform-specific and in this case it is 4 bytes = 32 bits.

An array variable has pointer semantics, so when it is passed to a function or used in an assignment such as int *p = arr, it represents the address of its first element, however its type is not simply the type of its elements.

In your snippet the size is inferred by the compiler from the initializer you used, so your array type is int[3] in this case,and not simply int.

DNT
  • 2,356
  • 14
  • 16
  • This is not strictly correct - an *expression* of array type will be converted to an expression of pointer type under most circumstances. The array *variable* is not a pointer. – John Bode May 17 '20 at 00:53
  • @JohnBode I said that the variable has pointer semantics. Having semantics of type T means the compiler can coerce it to T where appropriate as is the case in an assignment to another type T variable, but not when measuring its size with sizeof. This is not the same as saying the variable IS of type T. – DNT May 17 '20 at 05:59
0

although "arr" is also being a pointer

NO, array is not a pointer.

The sizeof pointer depends on the architecture. It does not depend on what it points to.

The size of array is amount of all element in array. In this case, arr content of 3 integer elements, each element has 4 bytes in your system, (the size of int may be 2 in other systems). So the size of arr is 3*sizeof(int) = 3*4 = 12.

See What is the size of a pointer?

Very useful for your question How to find the 'sizeof' (a pointer pointing to an array)?

And How do I determine the size of my array in C?

Hitokiri
  • 3,607
  • 1
  • 9
  • 29