简体   繁体   中英

How is Memory Allocated to variables of different data types?

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.

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.

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.

每个整数占用四个字节,因此每个整数内存地址偏移4。一个char只占用一个字节,因此其内存地址偏移1。

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