0

The output of size of for

#include<iostream>
using namespace std;
struct node
{
    int k;
    struct node *next;
};
int main()
{
    int arr[3];
    cout<<sizeof(struct node)<<endl;
    cout<<sizeof(struct node *)<<endl;
    cout<<sizeof(arr)<<endl;
    cout<<sizeof(arr[0])<<endl;
    cout<sizeof(int *)<<endl;
    return 0;
}

is

8
4
12
4
4

I understand that struct node * is a pointer so its output should be 4. So similarly arr is also a pointer, so its output should also be 4 but why is it showing the size of arr array as 12?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
doubt
  • 315
  • 3
  • 18

3 Answers3

4

So similarly arr is also a pointer, so its output should also be 4 but why is it showing the size of arr array as 12?

When array name is an operand of the sizeof or the unary & then it doesn't convert to pointer to its first element. Conversion rule is not applied in these cases.
In case of

cout<<sizeof(arr)<<endl; 

The sizeof returns the size of the type of arr, which is of type int[3] (array of 3 ints).

C11: 6.5.3.4:

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.

haccks
  • 104,019
  • 25
  • 176
  • 264
4

So similarly arr is also a pointer

No, arr is not a pointer, it is an array. Although it can be freely converted to a pointer, it is a different kind of object. The results of sizeof indicate the amount of memory necessary to store the array of the specified size, i.e. three times the size of an int.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

This is because the type of arr is int[3], not int* as you've assumed. So sizeof returns the size of the entire array.

Zacrath
  • 521
  • 3
  • 8