sizeof和alignof有什么区别?
#include <iostream>
#define SIZEOF_ALIGNOF(T) std::cout<< sizeof(T) << '/' << alignof(T) << std::endl
int main(int, char**)
{
SIZEOF_ALIGNOF(unsigned char);
SIZEOF_ALIGNOF(char);
SIZEOF_ALIGNOF(unsigned short int);
SIZEOF_ALIGNOF(short int);
SIZEOF_ALIGNOF(unsigned int);
SIZEOF_ALIGNOF(int);
SIZEOF_ALIGNOF(float);
SIZEOF_ALIGNOF(unsigned long int);
SIZEOF_ALIGNOF(long int);
SIZEOF_ALIGNOF(unsigned long long int);
SIZEOF_ALIGNOF(long long int);
SIZEOF_ALIGNOF(double);
}
Run Code Online (Sandbox Code Playgroud)
将输出
1/1 1/1 2/2 2/2 4/4 4/4 4/4 4/4 4/4 8/8 8/8 8/8
我想我不知道对齐是什么......?
#include <stdio.h>
#include <string.h>
int main(void)
{
char ch='a';
printf("sizeof(ch) = %d\n", sizeof(ch));
printf("sizeof('a') = %d\n", sizeof('a'));
printf("sizeof('a'+'b'+'C') = %d\n", sizeof('a'+'b'+'C'));
printf("sizeof(\"a\") = %d\n", sizeof("a"));
}
Run Code Online (Sandbox Code Playgroud)
该程序用于sizeof计算大小.为什么尺寸'a'不同于ch(哪里ch='a')?
sizeof(ch) = 1
sizeof('a') = 4
sizeof('a'+'b'+'C') = 4
sizeof("a") = 2
Run Code Online (Sandbox Code Playgroud) 当我sizeof(int)在C#.NET项目中执行时,返回值为4.我将项目类型设置为x64,那为什么它会说4而不是8?这是因为我正在运行托管代码吗?
如何在C中编译时打印sizeof()的结果?
现在我使用静态断言(基于其他Web资源自酿)来将sizeof()结果与各种常量进行比较.虽然这有效但它远非优雅或快速.我还可以创建变量/ struct的实例并查看映射文件,但这比直接调用/命令/运算符更不优雅和快速.此外,这是一个使用多个交叉编译器的嵌入式项目......因此,为目标构建和加载示例程序然后读出一个值比上述任何一个都更麻烦.
在我的情况下(旧的GCC),#warning sizeof(MyStruct)在打印警告之前实际上并没有解释sizeof().
我试过了
printf("%d, %d\n", sizeof(char), sizeof('c'));
得到1,4作为输出.如果一个角色的大小是一个,为什么'c'给我4?我想这是因为它是一个整数.所以,当我这样做时,是否会char ch = 'c';发生隐式转换,在它被分配给char变量时,从4字节值到1字节值?
我使用sizeof来获取C中结构的大小,但我得到的结果是意外的.
struct sdshdr {
int len;
int free;
char buf[];
};
int main(){
printf("struct len:%d\n",(sizeof(struct sdshdr)));
return 0;
} //struct len:8, with or without buf
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么不buf占用任何空间,为什么int64位CPU上的类型大小仍为4?
这是输出gcc -v:
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.4.0
Thread model: posix
Run Code Online (Sandbox Code Playgroud) C/C++中联合的大小是多少?它是最大数据类型的sizeof吗?如果是这样,如果联合的较小数据类型之一处于活动状态,编译器如何计算如何移动堆栈指针?
#include "stdio.h"
#include "string.h"
main()
{
char string[] = "october"; // october is 7 letters
strcpy(string, "september"); // september is 9 letters
printf("the size of %s is %d and the length is %d\n\n", string, sizeof(string), strlen(string));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
9月的大小是8,长度是9
我的语法有什么问题或者是什么?
从下面的代码sizeof(Base) == 24和sizeof(Derived) == 24.
为什么他们的尺寸相同?
在Base课堂上我们有3名成员,在Derived课堂上我们有另一名成员.
class Base
{
private:
double d;
protected:
long l;
public:
int i;
};
class Derived : public Base
{
private:
float f;
};
Run Code Online (Sandbox Code Playgroud) #include <stdio.h>
int main(void)
{
if (sizeof(int) > -1)
printf("True");
else
printf("False");
}
Run Code Online (Sandbox Code Playgroud)
它打印False.为什么sizeof()不返回值if?