'sizeof()' 在 Windows 和 Linux 上返回不同的值

`sizeof()` returns different values on Windows and Linux

本文关键字:返回 Windows sizeof Linux      更新时间:2023-10-16

程序

我使用 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操作系统上打印48在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)

问题

  1. 为什么会有区别?
  2. 如何更改代码,以便在每个操作系统上打印成员变量_palette中正确数量的数组?
  3. 可选:有没有更简洁的方法来实现我的目标,没有多维数组?是在 C++98 还是 C++11?

你的函数palette返回一个指针;sizeof告诉你sizeof系统上的指针。显然,Linux 和 Windows 机器上的指针sizeof是不同的,这就是您获得不同结果的原因。 sizeof无法跟踪附加到指针的内存量,您必须自己手动跟踪。