c++ - 从数组指针获取奇怪的数字

标签 c++ arrays pointers

我制作了将给定值(从数组指针)拆分为字节的函数。为简单起见,我使用一个字节值。 为什么我在打印值时得到奇怪的数字?

void writePage(uint16_t address, uint64_t *data, uint8_t const len, uint8_t const bPD)
{
    uint8_t pageBuffer[32];
    uint8_t bytes2Write = len * bPD;

    for (uint8_t dataIndex = 0; dataIndex < len; dataIndex++)
    {
        std::cout << int(dataIndex) << std::endl;
        std::cout << data[dataIndex] << std::endl;
        for (uint8_t i = 0; i < bPD; i++)
        {
            pageBuffer[i + (dataIndex * bPD)] = ((data[dataIndex] >> 8 * i) & 0xFF);
            std::cout << int(pageBuffer[i + (dataIndex * bPD)]) << std::endl << std::endl;
        }
    }
}

int main()
{
    uint8_t array[3] = { 255, 20, 30 };
    std::cout << int(array[0]) << int(array[1]) << int(array[2]) << std::endl;
    writePage(0, (uint64_t*)array, 3, 1);

    getch();
    return 0;
}

输出

2552030

0

119944479905023

255

1

70453687222272

0 2

0

0

最佳答案

如果你的目标是采用任何类型,并分解字节,几乎总是这样做的方式是将指向该类型的指针转​​换为 char * 并使用 字符*

这是一个使用您的代码精简版的示例。

#include <iostream>

struct foo
{
    int x;
    double y;
    char z;
};

void writePage(uint16_t address, char *data, uint8_t const len)
{
    for (uint8_t dataIndex = 0; dataIndex < len; dataIndex++)
    {
        std::cout << (int)data[dataIndex] << std::endl;
    }
}

int main()
{
    uint8_t array[3] = { 255, 20, 30 };
    std::cout << int(array[0]) << " " << int(array[1]) << " " << int(array[2]) << std::endl;
    writePage(0, reinterpret_cast<char *>(&array[0]), sizeof(array));
    foo f;
    f.x = 10;
    f.y = 20;
    f.z = 'g';
    std::cout << "Here are the bytes of foo, which has a sizeof(foo) as " << sizeof(foo) << "\n" ;
    writePage(0, reinterpret_cast<char *>(&f), sizeof(f));
    return 0;
}

输出:

255 20 30
-1
20
30
Here are the bytes of foo, which has a sizeof(foo) as 24
10
0
0
0
0
0
0
0
0
0
0
0
0
0
52
64
103
-54
-117
-54
-2
127
0
0

关于c++ - 从数组指针获取奇怪的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56917751/

相关文章:

c++ - 如何创建函数指针数组?

python - 查找列表中第 n 个项目的索引

javascript - 在特定索引处合并两个数组

c++ - 如何创建可以影响通过构造函数传递的对象的类变量?

c# - 具有大量客户端的套接字编程中的客户端到客户端通信

c++ - OpenGL 3.+ 中的阵列纹理与 mipmap

C++ 并行 std::vector 排序与昂贵的复制

c - 初始化字符串值 vector

c - 为什么指向指针的指针可以表现得像数组?

c++ - 来自指针 vector 的 OpenGL 数组缓冲区