C double variable takes up too much space

Okay, so I was playing around with pointers, and I noticed something. when I used a pointer to display the memory address of a double variable, it said it took up 12 bytes, when it should only have taken up 8 bytes. Also, it only took up 12 bytes when the data that proceeds it in memory is not of the double type.

Here's my code:

int main(void)
int t = 1;
double u = 10.1;
float v = 20.1f;
double w = 30.1;
double x = 40.1;
int y = 50;
double z = 60.1;

int *tPtr = &t;
double *uPtr = &u;
float *vPtr = &v;
double *wPtr = &w;
double *xPtr = &x;
int *yPtr = &y;
double *zPtr = &z;

printf("t is an integer and has the number %d in it
", t);
printf("t is located at %u
", tPtr);
printf("u is a double and has the number %lf in it
", u);
printf("u is located at %u
", uPtr);
printf("v is a float and has the number %f in it
", v);
printf("v is located at %u
", vPtr);
printf("w is double and has the number %lf in it
", w);
printf("w is located at %u
", wPtr);
printf("x is a double and has the number %lf in it
", x);
printf("x is located at %u
", xPtr);
printf("y is an integer and has the number %d in it
", y);
printf("y is located at %u
", yPtr);
printf("z is a double and has the number %lf in it
", z);
printf("z is located at %u
", zPtr);

and here's the output:

As you can see, each double (except for double [i]x[/i] which follows double [i]w[/i] takes up 12 bytes. I've also tried compiling this with gcc, and Visual Studio 2005.


  • [color=Blue]The proper size of any variable is taken with sizeof() operator and not by calculating address difference:[/color]
    double value;
    printf ("
    Type 'double' takes %d bytes for storage.
    ", sizeof (value));
    [/code][color=Blue]The results you seeing are the effect of stack alignment - stack must be aligned on 8 or 16 byte frame. If variables on stack are crossing these boundaries - the storage room is aligned for:

    1. Performance - aligned variables are faster to access by CPU
    2. Stack room in general (see Intel Manuals) must be aligned, otherwise program will crash.[/color]
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion