开发者

Pointer Addition

I do not understand why the pointer addition is failing.

DWORD开发者_如何学JAVA *pipebuf=new DWORD[10001];

Command *cr= (Command*)pipebuf;
cr->command=2;
DWORD* rooms=(pipebuf+1); //should work fine..sets the room pointer equal to pipe[2]
*rooms=buff3;  //where buff3=100

Yet, the value of pipebuf only contains the value of command, it does not contain the value of buff3. Yet, when I remove the new keyword it works fine...Why?

DWORD=unsigned_int

Command is a class with a DWORD variable of command.. something like this

Class Command {
DWORD command;
}


The addition moves the pointer forward one, causing it to point at the second DWORD in your array. *(pipebuf+1) is precisely equivalent to pipebuf[1]; after your code runs, *pipebuf aka pipebuf[0] aka cr->command is equal to 2, while *(pipebuf+1) aka *rooms aka pipebuf[1] is equal to 100.

Note however that typecasting between pointer types in C++ is often considered bad style and can in many circumstances have undesirable results. If you are allocating an array of Command's, then use new Command[...]; if you want DWORD's, then don't cast into Command*.

Sometimes you have to cast pointers between types, but generally you should only do that if you know exactly what you're doing and why you can't avoid doing so.

Furthermore, if you do need to, you should either be using static_cast (in cases like this) or dynamic_cast (in cases where the types are related by inheritance; this usage is much safer generally).


class Command is a user defined type and DWORD is a primitive data type ( unsigned int ). In that case, why doing this -

Command *cr= (Command*)pipebuf;

class Command {
    public :     // Added public keyword
    DWORD command;  // DWORD is a typedef for unsigned int as you mentioned.
};  // class definition should end with a semi-colon

So, this is the way to do -

Command *cr = new Command[10001] ;
DWORD *pipebuf=new DWORD[10001];

// After assigining values to DWORD pointed locations. Then you can do this -

cr->command = pipebuf[0] ; // this sets the value of cr[0].command.


I'd make this a comment, but I can't do code formatting in those.

I ran this code, and the output is "2 100" as expected:

#include <iostream>

using namespace std;

typedef unsigned int DWORD;
class Command {
  public:
    DWORD command;
};

int main()
{
    DWORD buff3 = 100;
    DWORD *pipebuf = new DWORD[10001];
    Command *cr = (Command*)pipebuf;
    cr->command = 2;
    DWORD *rooms = (pipebuf+1);
    *rooms = buff3;

    std::cout << pipebuf[0] << " " << pipebuf[1] << endl;
}

AFAICT that's the simplest way you could expand your question into a complete program.

Could you try taking this and adding more stuff from the original code until you get the problem to appear?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜