Delphi新手请教指针运算的超简单问题!!(100分)

  • 主题发起人 叮叮当当
  • 开始时间

叮叮当当

Unregistered / Unconfirmed
GUEST, unregistred user!
请教!怎么这么简单的一段程序都不能通过?
var
P: Pointer;
I: Integer;
begin
P := P + I;
end;
编译时报错 "Operator not applicable to this operand type" !
P := P + 1 也不行![:(]
Inc(P)
倒可以,为什么??

查看 Delphi 中关于 Pointer 类型的说明如下:

The relational operators <, >, <=, and >= can take operands of type PChar (see Relational operators). The following operators also take pointers as operands. For more information about pointers, see Pointers and pointer types.

Operator Operation Operand types Result type Example
+ pointer addition character pointer, integer character pointer P + I
- pointer subtraction character pointer, integer character pointer, integer P - Q
^ pointer dereference pointer base type of pointer P^
= equality pointer Boolean P = Q
<> inequality pointer Boolean P <> Q
The ^ operator dereferences a pointer. Its operand can be a pointer of any type except the generic Pointer, which must be typecast before dereferencing.
P = Q is True just in case P and Q point to the same address
otherwise, P <> Q is True.

可见 Pointer 指针类型明明是可以和 Integer 进行 +、-运算的呀!
 
var
P: Pointer;
I: Integer;
begin
i:=$1;
P := Pointer(Integer(P) + I);
end;
 
Pointer是无符号类型,而Integer是有符号的,计算出来的值在某些情况下会不会有问题?
 
选一个32位的无符号类型,我一般是这样用,但Integer也没试过出错。
为了能在以后能编译,最好不要用指针。
 
To: testnet
> 为了能在以后能编译,最好不要用指针。
这句话是什么意思?
 
Help文档说得很清楚,指针的 +,- 操作只能用于PChar类型的指针,你可以试试
Var
buf:array [0..50] of char
p:pChar;
Begin
P:=@buf;
StrCopy(p,'Hello World);
ShowMessage(p)
//显示 Hello World
P:=P+1;
ShowMessage(p)
//显示 ello World
End


另外不同类型的变量不能互相操作,体现了Pascal的语法严谨性,不象C一样自由散漫,只能
进行强制转换类型后才能进行操作。

操作Pascal指针,最容易方法是用inc(),如
指定递进的指针地址用 inc(p,5) 相当于 p:=Pointer(Integer(p)+5)
指向结构的指针用 inc(p,sizeof(p^)) 相当于 p:=Pointer(Integer(p)+Sizeof(p^))
 
刚才试过了,Inc函数不接受Pointer类型的,我前面写错了,如果是^Integer可以用Inc来递增。
 
P := pointer(integer(P) + I);
 
p:=pointer(dword(p)+i);
要用无符号的32位整数用integer来转化不好.
 
//用integer来转化不好.
无所谓,VCL 源码中就有这样用的:)
 
TO: beta
是的,我多虑了,用有符号的Integer也不会有问题的。[:)]
 

Similar threads

I
回复
0
查看
542
import
I
I
回复
0
查看
676
import
I
I
回复
0
查看
1K
import
I
I
回复
0
查看
2K
import
I
I
回复
0
查看
2K
import
I
顶部