How is Memory Allocated to variables of different

2019-01-27 12:15发布

问题:

I wrote the following Code.

#include<stdio.h>

int main()
{
    int x = 1 ;
    int *j = &x ;
    int y =  2 ;
    int *t = &y ;

    printf("%p\n" , (void *)j);
    printf("%p" , (void *)t);
}   

Output is 0028FF14 0028FF10.

The Point I want to make is that the difference between the addresses is `4'.

Whereas in this case

#include<stdio.h>

int main()
{
    char x = 't' ;
    char *j = &x ;
    char y =  'f' ;
    char *t = &y ;
    printf("%p\n" , (void *)j);
    printf("%p" , (void *)t);    

   }   

Output is 0028FF17 0028FF16

The difference is 1.

Difference In First Case is 4. Whereas in the second case it is 1. Why is it so?

And What will I get if I printed value at all memory addresses individually?

Maybe It is really general and known, but I just started C, So the output of the program confuses me.

Update
Now Using %p format and converted the pointer value to void* to print the pointer value as suggested by Keith Thompson.

回答1:

There are no requirements on the order in which declared objects are laid out in memory. Apparently the compiler you're using happens to place x and y next to each other. It could have placed j between them, but it didn't.

Also, the correct way to print a pointer value is to use the %p format and convert the pointer value to void*:

printf("%p\n", (void*)j);
printf("%p\n", (void*)t);

This produces an implementation-defined human-readable representation of the pointer value, typically but not always in hexadecimal.

If you care about the order in which declared variables are allocated in memory, you're probably doing something wrong, or at least not useful. Let the compiler worry about where to put things. It knows what it's doing.



回答2:

Well for starters the difference isn't always four, it just happens to be four by happy coincidence. The compiler is allowed to stick variables in memory where ever it wants to. In this case it has put your two variables next to each other in memory and the difference can be explained as that is how big an integer is on your system(4 bytes) and how big a character is on your system(1 byte). On other systems they may be different sizes and placed in different locations.



回答3:

Each integer takes up four bytes, therefore, each integer memory address is offset by 4. A char only takes up one byte, therefore its memory addresses are offset by one.