Home > Net >  sizeof pointer and variable is not the same
sizeof pointer and variable is not the same

Time:04-17

why value a and x is different? I think it should be the same

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
   
  int a =5;
  int *x=&a;

  printf("%ld\n", sizeof(a)); // print 4
  
  printf("%ld\n", sizeof(x)); // print 8
   
   return(0);
}

CodePudding user response:

I am not sure whether you are aware of what you are actually measuring with the sizeof operator.

First you measure integer a, which is the size of an int (4 bytes). And second you measure not an integer but a pointer which stores the address of integer a, so the value is different and I think the value of x is 8 bytes.

  • int a (4 bytes INTEGER)
  • int *x = &a (is address of a)

But I can be wrong.

CodePudding user response:

why value a and x is different? I think it should be the same

a is an int and x is a pointer.

int a = 5;
int *x = &a;

C does not specifier an int and a pointer need to be the same size. They may have the same size. Commonly a pointer is as wide as an int or wider, yet either one may be wider than the other.

It is implementation defined.


Since C99, use "%zu" to print a size_t, which is the resultant type from sizeof.

// printf("%ld\n", sizeof(a));
printf("%zu\n", sizeof(a));
// or 
printf("%zu\n", sizeof a); // () not needed about objects.
  •  Tags:  
  • c
  • Related