变量如何与C中的值绑定? [英] How are variables tied to their values in C?

查看:63
本文介绍了变量如何与C中的值绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有一行这样的代码

If you have a line of code like

int num = 4;

这是否在下表中显示?

VARIABLE|ADDRESS   ADDRESS|VALUE
num     |0001      0001   |4

如果您要说

int* num_p = #

此结果将在下表中显示吗?

Would this result in the following tables?

VARIABLE|ADDRESS   ADDRESS|VALUE
num     |0001      0001   |4
num_p   |0002      0002   |0001

然后会说

int** num_pp = &num_p;

下表中的结果?

VARIABLE|ADDRESS   ADDRESS|VALUE
num     |0001      0001   |4
num_p   |0002      0002   |0001
num_pp  |0003      0003   |0002

以此类推?如果是这样,如果初始变量不是int而是struct,那么同样的逻辑是否成立?

And so on? If so, would this same logic hold true if the initial variable were not an int but instead a struct?

请检查此问题的注释,以获取有关与000100020003方案组成的地址实际不同的地址的信息.

Check the comments on this question for info on what the addresses would actually look like as opposed to this made up 0001, 0002, 0003 scheme.

此问题的答案指出了这样一个事实,即变量不一定必须具有地址. 对先前问题的答案也涉及到这一点.

EDIT 2: This answer to this question points out the fact that variables do not necessarily have to have an address. This answer to an earlier question also goes into this.

推荐答案

是的,用表说明的内容大致正确.变量名在编译时分配给地址.这称为符号表",类似于您问题中的左侧表.程序运行时,变量名不再显示在可执行文件中,并且只有像右表中一样的地址.

Yes, what you illustrate with your tables is roughly correct. Variable names are assigned to addresses at compile time. This is called a "symbol table" and is analogous to the left-hand tables in your question. When the program runs, the variable names no longer appear in the executable and there are only addresses like you have in your tables on the right.

如果是这样,如果初始变量不是一个int而是一个struct,那么同样的逻辑是否成立?

If so, would this same logic hold true if the initial variable were not an int but instead a struct?

是的,struct是一个值,因此为变量分配地址和为该地址分配值的方式相同.不同之处在于,根据其成员,struct可能比int占用更多的内存.这会影响下一个变量可使用的地址.

Yes, a struct is a value, so assigning an address to a variable and a value to that address works the same way. The difference is that a struct might take more memory than an int depending on its members. This affects what address is available for the next variable.

请注意,分配的地址将与某些基本存储器地址发生偏移.当操作系统加载可执行文件时,它将提供此基址,并且可执行文件通过将偏移量添加到基址来计算绝对内存地址.

Note that the addresses assigned will be offsets from some base memory address. When the OS loads the executable, it gives this base address and the executable calculates the absolute memory addresses by adding the offsets to the base address.

如果您有兴趣了解有关其工作原理的更多信息,则可以更详细地研究编译器和操作系统.

If you are interested in learning more about how this works, you can study compilers and operating systems in more detail.

这篇关于变量如何与C中的值绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆