2011-03-19 57 views
0

我不明白为什么指针加法失败。指针加法

DWORD *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 

然而,pipebuf的值只包含命令的值,它不包含buff3的值。然而,当我删除新的关键字,它工作正常......为什么?

DWORD = unsigned_int

命令与命令的DWORD变量类..像这样

Class Command { 
DWORD command; 
} 
+0

什么是DWORD和命令? – Mahesh 2011-03-19 09:12:08

+0

DWORD = unsigned_int。命令是一个包含命令的DWORD变量的类 – Jake 2011-03-19 09:14:13

+0

这是什么语言? C++? – Mat 2011-03-19 09:15:02

回答

0

Command类是用户定义的类型和DWORD是基本数据类型(unsigned int) 。在这种情况下,为什么这样做 -

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 

所以,这是应该做的方式 -

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. 
2

加入移动指针向前,使其以点数组中的第二个DWORD。 *(pipebuf+1)恰恰相当于pipebuf[1];你的代码运行后,*pipebuf又名pipebuf[0]又名cr->command等于2,而*(pipebuf+1)又名*rooms又名pipebuf[1]等于然而100

注意在C++中的指针类型之间的类型转换常常被认为是不好的风格,可以在许多情况下有不良结果。如果你正在分配一个Command的数组,然后使用new Command[...];如果你想要DWORD的话,那么不要投入Command*

有时你必须在类型之间投射指针,但通常你只应该这样做,如果你知道正好是你在做什么以及为什么你不能避免这样做。此外,如果您确实需要,您应该使用static_cast(在这种情况下)或dynamic_cast(在类型通过继承关联的情况下;这种用法通常更安全)。

+0

是的.. *房间应该相当于pipebuf [1],它应该设置管道[1]等于100 ....但它没有这样做...是的,我知道它的不好的风格,但在这种情况下,它是更容易掌握代码。 – Jake 2011-03-19 09:35:04

+0

最让我困惑的是它是通过从动态指针改变它来修复的。那就是删除新的关键字。 – Jake 2011-03-19 09:40:39

+0

对于投射指针来说是不好的 – rve 2011-03-19 09:50:06

0

我想这是一个评论,但我不能在那些代码格式。

我跑这个代码,并输出为“2 100”预期:

#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这就是你可以扩展你的问题变成一个完整的程序最简单的方法。

你可以尝试采取这种做法,并从原始代码中添加更多东西,直到出现问题为止?