简体   繁体   中英

Address as a operand in sizeof() operator

I was just trying an example and i tried to check the output when an address is passed as an argument in the sizeof operator and i got output of 4. Now my question is when you pass a pointer in sizeof operator why is it showing 4 bytes of memory when actually there is no pointer variable, it's just only an address?

#include<stdio.h>
int main()
{
  int a=1;
  int c;
  c=sizeof(&a);
  printf("%d\n",c);
  return 0;
}

It's because sizeof returns the size of a type, as per C11 6.5.3.4 The sizeof and _Alignof operators /2 (my emphasis):

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 type of &a where a is an int is covered by 6.5.3.2 Address and indirection operators /3 in the same standard:

The unary & operator yields the address of its operand. If the operand has type "type", the result has type "pointer to type".

In other words, int a; sizeof(&a) int a; sizeof(&a) is functionally equivalent to sizeof(int *) .

sizeof operator works on the type of the operand.

Quoting C11 , chapter §6.5.3.4 ( emphasis mine )

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. [....]

&a is of type int * , so your statement is the same as sizeof(int *) . The result, is the size of a pointer (to integer), in your platform.

That said, sizeof produces a type of size_t as result,

  • use a variable of type size_t
  • use %zu to print the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM