【发布时间】:2008-12-19 09:07:22
【问题描述】:
假设我有一些指针叫做:
char * pChar;
int * pInt;
我知道它们都只是保存指向其他位置的内存地址,并且类型声明了特定指针指向的内存位置有多大。例如,一个 char 可能是系统上一个字节的大小,而一个 int 可能是 4 个字节。所以当我这样做时:
pChar++; // I am actually incrementing the address pointed to by pChar by 1 byte;
pInt++; // I am actually incrementing the address pointed to by pInt by 4 bytes;
但是如果我这样做呢:
pChar+2; // increment the address pointed to by pChar by 2 bytes?
pInt+2; // increment the address pointed to by pInt by 2 bytes? what happens to the other two bytes?
谢谢.. 如有任何澄清.. 指针类型是否仅用于 ++ 操作?
编辑:所以 avp 恰当地回答了我的问题,但我有一个后续问题,当我这样做时会发生什么:
memcpy(pChar,pInt,2);
它会复制 2 个字节吗?还是4个字节?我会有访问冲突吗?
编辑:根据 Ryan Fox 的说法,答案是 2 个字节,因为它们被强制转换为 (void*)。谢谢!关闭!
编辑:只是为了让未来的搜索者可以找到这个.. 我发现的另一条信息..
memcpy(pChar+5,pInt+5,2);
不会将 pInt+5bytelocations 指向的内存块的 2 个字节复制到 pChar+5bytelocations.. 发生的情况是 2 个字节从 pInt(4*5)bytelocations 复制到 pChar+5bytelocations.. 难怪我得到了访问违规,我试图在我不应该阅读的地方阅读.. :)
【问题讨论】:
-
我不确定“typecasted”是正确的术语。我将 void* 视为其他指针类型的一种抽象父类。 void* 参数将接受任何指针,就像具有父类类型的参数将接受子类值一样。