int x = 32000;
int y = 32000;
int z = x+y; // can cause overflow for 2 bytes, but not 4
在第二种情况下,
struct header {
int magic;
int w;
int h;
};
然后有人写道:
header h;
// fill in h
fwrite(&h, sizeof(h), 1, fp);
// this is all fine and good until one freads from an architecture with a different int size
在第三种情况下:
int* x = new int[100];
char* buff = (char*)x;
// now try to change the 3rd element of x via buff assuming int size of 2
*((int*)(buff+2*2)) = 100;
// (of course, it's easy to fix this with sizeof(int))
如果您正在使用一个相对较新的编译器,我会使用 uint8 _ t、 int8 _ t 等。为了保证型号的大小。
在较老的编译器中,typedef 通常是在每个平台的基础上定义的:
#ifdef _WIN32
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
// and so on...
#endif