Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

c - 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
" , (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
" , (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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", (void*)j);
printf("%p
", (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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...