gpt4 book ai didi

C++指针算术怪异

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:08:43 27 4
gpt4 key购买 nike

我发现了我的错误(几个小时后)并将其隔离在以下程序中。问题在于使用指向结构的指针时计算 pst2 变量值的方式。使用指向 char 的指针时,一切正常。这是为什么?
(使用 gcc/g++ 版本:(Debian 4.4.5-8)4.4.5)
(对于那些想知道的人:我正在访问一个包含数据分组的文件缓冲区以常规偏移量。)

#include <iostream>
#include "testpa.h"

#pragma pack(push)
#pragma pack(1)
//---------------------------
struct st_one
{
int i;
char c;
};
//---------------------------
struct st_two
{
long l;
int i;
};
#pragma pack(pop)

//===========================
int main()
{
int n=1024, np1=sizeof(st_one); //, np2=sizeof(st_two);
st_one *pst1, *pst1a;
st_two *pst2, *pst2a;
char *pc1, *pc2, *pc1a, *pc2a, *pb;

pb = new char[n];

pst1 = (st_one*)(pb);
pst2 = (st_two*)(pst1 + np1); //using pst1
pc1 = (char*)(pb);
pc2 = (char*)(pc1 + np1); //using pc1

pst1a = (st_one*)(pb);
pst2a = (st_two*)(pb + np1); //using pb
pc1a = (char*)(pb);
pc2a = (char*)(pb + np1); //using pb

std::cout << "\npb = " << (long)pb;
std::cout << "\n-----";
std::cout << "\npst1 = " << (long)pst1 << "\tpst2 = " << (long)pst2;
std::cout << "\npc1 = " << (long)pc1 << "\tpc2 = " << (long)pc2;
std::cout << "\n-----";
std::cout << "\npst1a = " << (long)pst1a << "\tpst2a = " << (long)pst2a;
std::cout << "\npc1a = " << (long)pc1a << "\tpc2a = " << (long)pc2a;
std::cout << "\n-----\n";

return 0;
}

输出:

pb = 19546128

pst1 = 19546128 pst2 = 19546153 <--- WRONG!
pc1 = 19546128 pc2 = 19546133

pst1a = 19546128 pst2a = 19546133
pc1a = 19546128 pc2a = 19546133

最佳答案

我觉得不错。线路:

 (pst1 + np1)

st_onenp1 实例添加到 pst1 指向的地方,这意味着 pst1 的值增加by np1 * sizeof (st_one) 字节,即 25 (sizeof = 5),对应于您输出的值。而不是上面的,我想你想要的是:

 (pst1 + 1)

pc1 值起作用是因为它是一个 char 指针,所以行:

(pc1 + np1)

np1 * sizeof (char) 字节添加到 pc1,即 5 个字节。

递增指针使指针指向内存中的下一个元素,而不是下一个字节。

关于C++指针算术怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6847538/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com