'sizeof()' 在 Windows 和 Linux 上返回不同的值
`sizeof()` returns different values on Windows and Linux
程序
我使用 Eclipse 来编写、编译、构建和运行这段代码。在Windows和Linux上。
Card.h
class Card {
private:
static int _palette[][3];
public:
static int (*palette())[3];
};
Card.cpp
#include "Card.h"
int Card::_palette[][3]= {
{168, 0, 32},
{228, 92, 16},
{248, 216, 120},
{88, 216, 84},
{0, 120, 248},
{104, 68, 252},
{216, 0, 204},
{248, 120, 248}
};
main.cpp
#include <iostream>
#include "Card.h"
int main(int argc, char **argv) {
int uniqueColors= sizeof(Card::palette());
std::cout << uniqueColors << std::endl;
return 0;
}
这在我的Windows10操作系统上打印4
,8
在Debian 8.2 Jessie上打印。
视窗构建日志
这是我使用 MinGW GCC 工具链和 CDT Internal Builder 构建时在 64 位 Win10 上的 Eclipse 控制台:
16:53:09 **** Rebuild of configuration Debug for project sizeOf-test ****
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o Card.o "..\Card.cpp"
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o "..\main.cpp"
g++ -o sizeOf-test.exe Card.o main.o -lmingw32
16:53:11 Build Finished (took 1s.934ms)
当我运行该程序时,它会打印4
.
Linux 构建日志
以下是 64 位 Debian 8.2 Jessie 上的 Eclipse 控制台,使用 Linux GCC 工具链和 CDT Internal Builder:
17:17:57 **** Incremental Build of configuration Debug for project cpp-sizeof-test ****
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o ../main.cpp
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o Card.o ../Card.cpp
g++ -o cpp-sizeof-test Card.o main.o
17:17:57 Build Finished (took 327ms)
问题
- 为什么会有区别?
- 如何更改代码,以便在每个操作系统上打印成员变量
_palette
中正确数量的数组? - 可选:有没有更简洁的方法来实现我的目标,没有多维数组?是在 C++98 还是 C++11?
你的函数palette
返回一个指针;sizeof
告诉你sizeof
系统上的指针。显然,Linux 和 Windows 机器上的指针sizeof
是不同的,这就是您获得不同结果的原因。 sizeof
无法跟踪附加到指针的内存量,您必须自己手动跟踪。
相关文章:
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 几个 Nt 函数在 Windows 7 x32 上返回STATUS_WAIT_0
- 尝试在 Windows 上重定向 stdout 和 stderr——_fileno(stdout) 返回 -2
- 从我的2d数组中的一列返回的字符串值被压缩为一个字符串(在Mac os上打开Windows txt文件)
- Qt5 哈希函数在 Windows 7 和 Windows10 上不会返回相同的哈希
- Windows 函数"GetCursorInfo"返回成功,但光标的句柄为 NULL
- C++ 即使数据可用,Windows recv() 也不会返回
- 如何检查 CNG Windows API 是否返回符合 FIPS 的算法实现
- C++ Windows 返回与退出进程
- repopenKeyex在Windows 8.1上返回2
- Windows句柄始终返回Invalid_handle_value
- 检查Windows激活状态返回错误的值
- 没有返回类型的静态函数可以通过Windows上的编译,但不能传递Linux上的编译
- 使用Outlook 2016:MAPISendMail在Windows应用程序中失败,并返回"MAPI_E_FAILURE"作为错误代码
- Windows HANDLE RAII 管理,如果返回布尔值而不是句柄怎么办?
- 为什么 CoCreateInstance 在某些 Windows 上返回REGDB_E_CLASSNOTREG?
- FCGX_GetParam REQUEST_METHOD可以在Windows中使用,但在Linux中返回NULL
- 创建 CTime @ 2am 不会返回正确的值(Windows CE,C++)
- 为什么返回Windows BOOL数据类型而不返回int