显示结构体字段在运行时堆栈中存储顺序的代码

标签 c stack structure

这是一次采访中提出的问题之一。不知道发贴好还是不发好。但答案会对我有帮助。

我们知道局部变量将存储在堆栈中,假设我们有这样的代码。

int main()
{
    struct ST1 {
        char ch1;
        short s;
        char ch2;
        long long ll;
        int i;
    }s1;
    function(s1);// pasing structure to function
// some code
}

function(struct ST1 s1) {
    // code to show the order in which the fields of the structure are stored on the run time stack
}

如何在函数中编写代码来显示结构体字段在运行时堆栈中的存储顺序?

最佳答案

How can it be possible to write a code in function to show the order in which the fields of the structure are stored?

我们不需要; C语言标准保证顺序:

[C99 §6.7.2.1] Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared.

关于显示结构体字段在运行时堆栈中存储顺序的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19180524/

相关文章:

java - 如何将元素添加到链表末尾

c++ - 为什么前向声明不适用于类?

c - 为什么 printf 在终端中显示一个额外的 % 字符?

c - 如何调用 char * arr[]

c - 在没有控制台或窗口的应用程序中等待按键

c - 堆栈问题: Local variables vs Arithmetics

你能用 O(1) 的运行时间翻转堆栈吗?

c - 为什么我不能在这段代码中用 C 分配数组元素后立即打印该元素?

java - Java中的类不就相当于c中的结构吗

c - 在循环中使用变量访问相似的结构