#include <iostream>
using namespace std;
struct node1{
char b[3];
int c[0];
};
struct node2{
int c[0];
};
struct node3{
char b[3];
};
int main() {
cout << sizeof(node1) << endl; // prints 4
cout << sizeof(node2) << endl; // prints 0
cout << sizeof(node3) << endl; // prints 3
}
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么编译器为node2中的int c [0]分配0个字节,但为node1的一部分分配1个字节.我假设这个1字节是sizeof(node1)返回4的原因,因为没有它(如在node3中)它的大小是3或者是由于填充?
还试图理解不应该node2有足够的空间来容纳一个指向数组的指针(作为灵活的数组/结构黑客的一部分,它将在代码中进一步分配?
东西.h
1 class Something
2 {
3 private:
4 static int s_nIDGenerator;
5 int m_nID;
6 static const double fudgeFactor; // declaration - initializing here will be warning
7 public:
8 Something() { m_nID = s_nIDGenerator++; }
9
10 int GetID() const { return m_nID; }
11 };
Run Code Online (Sandbox Code Playgroud)
文件
1 #include <iostream>
2 #include "Something.h"
3
4 // This works!
5 //const double Something::fudgeFactor = 1.57;
6
7 int main()
8 {
9 Something cFirst;
10 Something cSecond;
11 Something …Run Code Online (Sandbox Code Playgroud) 我试图理解结构变量的打包如何影响堆栈上的局部变量分配地址的方式.
#include <stdio.h>
struct s
{
short s1;
short s2;
short s3;
};
int main()
{
struct s myStruct1;
struct s myStruct2;
myStruct1.s1 = 1;
myStruct1.s2 = 2;
myStruct1.s3 = 3;
myStruct2.s1 = 4;
myStruct2.s2 = 5;
myStruct2.s3 = 6;
int i = 0xFF;
printf("Size of struct s: %d", sizeof(myStruct1));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我上面的程序中,我有2个struct变量和1个整数.GCC编译器决定分配这样的地址:
&i 0x00007FFFFFFFDF0C
&myStruct1 0x00007FFFFFFFDF10
&myStruct2 0x00007FFFFFFFDF20
Run Code Online (Sandbox Code Playgroud)
结构中没有填充 - 结构的大小是6个字节.
问题是为什么myStruct2在myStruct1之后的下一个6字节上放置在2字节边界上?
在C中编写一个可移植函数(没有汇编),返回其堆栈帧的大小
int stackframe_size()
{
}
Run Code Online (Sandbox Code Playgroud)
尝试解决它如下所示 - 使用VS 2010编译时,此函数返回228个字节.有没有办法验证其正确性?
int stackframe_size(int run)
{
int i ;
if(!run)
{
return ((int)(&i) - stackframe_size(++run));
}
return (int)(&i);
}
Run Code Online (Sandbox Code Playgroud)
调用为:
int main()
{
printf("\nSize of stackframe_size() is: %d bytes",stackframe_size(0)) ;
return 0;
}
Run Code Online (Sandbox Code Playgroud)