C ++指针算术怪异 [英] C++ pointer arithmetic weirdness

查看:60
本文介绍了C ++指针算术怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found my bug (after a few hours) and isolated it in the following program. The problem is with the way in which the pst2 variable's value is calculated when using pointers to a struct. When using pointers to char, all works fine. Why is this?
(Using gcc/g++ version: (Debian 4.4.5-8) 4.4.5)
(For those who are wondering: I'm accessing a file-buffer containing data-groupings at regular offsets.)

#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_one np1 个实例添加到 pst1 所指向的位置,这意味着 pst1 的值增加了通过 np1 * sizeof(st_one)字节,它是25(sizeof = 5),对应于您输出的值.除了上述以外,我认为您想要:

adds np1 instances of st_one to what pst1 points at, which means that pst1s value is incremented by np1 * sizeof (st_one) bytes, which is 25 (sizeof = 5), which corresponds to the values you've outputted. Instead of the above, I think you wanted:

 (pst1 + 1)

pc1 值起作用是因为这是一个 char 指针,因此该行:

The pc1 value works because that is a char pointer, so the line:

(pc1 + np1)

np1 * sizeof(char)字节添加到 pc1 中,这是5个字节.

adds np1 * sizeof (char) bytes to pc1, which is 5 bytes.

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

这篇关于C ++指针算术怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆