((Pointer)(P)+1)^什么时候可以工作? [英] When can ((Pointer)(P)+1)^ work?

查看:98
本文介绍了((Pointer)(P)+1)^什么时候可以工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究delphiXE2,而我正在研究PInteger. 如果我在我的delphi代码中做到了

I'am working on delphiXE2 and i was working on PInteger. if i did this in my delphi code

var
  P: PInteger;
  testInt: Integer;
  Scores: array[0..4] of Integer=(33,44,56,78,78);
begin
  P := @Scores;
  testInt := (P+1)^;
  WriteLn(testInt);
  ReadLn;
end;

我收到此错误.

[DCC Error] Project1.dpr(23): E2015 Operator not applicable to this operand type

PS:testInt := (P+1)^;是第23行

但是当我尝试这个

var
  PCh: PChar;
  testchar: char;
  str: array[0..4] of char=('a','b','c','d','e');
begin
  PCh := @str;
  testchar := (PCh+1)^;
  WriteLn(testchar);
  ReadLn;
end;

效果很好! 控制台可以打印"b"!

it works well! The console can print 'b'!

我不清楚这将如何发生以及何时((Pointer)(P)+1)^可以工作?

I'm not clear about how could this happen and when ((Pointer)(P)+1)^ can work?

推荐答案

指针算术要求编译器知道所指向元素的大小.对于指针"类型的无类型指针,这种知识永远不会为人所知.因此,您永远无法使用Pointer进行指针算术运算.

Pointer arithmetic requires the compiler to know the size of the element that is pointed to. That knowledge is never known for an untyped pointer of type Pointer. So you can never do pointer arithmetic with Pointer.

Delphi一直支持AnsiChar的指针算法.最近,添加了一个编译器指令 POINTERMATH ,以在所有计算机上启用指针算术键入的指针: http://blogs.embarcadero.com/abauer/2008/01/24/38852

Delphi has always supported pointer arithmetic for AnsiChar. More recently a compiler directive, POINTERMATH, was added to enable pointer arithmetic on all typed pointers: http://blogs.embarcadero.com/abauer/2008/01/24/38852

请注意,该指令启用了加法算术运算符和数组索引运算符[].

Note that the directive enables the additive orithmetic operators and the array indexing operator [].

因此,如果启用指针算术,则可以对除未类型化指针之外的所有指针执行算术.否则,仅支持字符类型的指针或字节的指针.

So, if you enable pointer arithmetic, you can perform arithmetic on all pointers other than untyped pointers. Otherwise it is only supported for pointers to character types or pointers to byte.

话虽如此,如果您改为编写P [1],您的代码将更加整洁.显然,这需要启用指针算法.

With that said, your code would be much cleaner if you wrote P[1] instead. Obviously that would require pointer arithmetic to be enabled.

这篇关于((Pointer)(P)+1)^什么时候可以工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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