人们注意到了一些意想不到的行为:Put_Line(Integer'Image(Var.all)); var:=var+5; --它给出了1,var+6然后是2,如果var+7那么0,var+8那么-1,谁能解释一下吗?
with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C.Pointers;
procedure Access_Pointer_Arithmetic is
type Myarr_Indices is range 1 .. 5;
type Myarr is array (Myarr_Indices range <>) of aliased Integer;
Myarr_Terminator : constant Integer := 0;
package Myarr_Pointer_Arithmetic is new Interfaces.C.Pointers
(Myarr_Indices, Integer, Myarr, Myarr_Terminator);
use Myarr_Pointer_Arithmetic;
Myarr_Var : aliased Myarr := (2, 5, 7, 9, 0);
Var : Myarr_Pointer_Arithmetic.Pointer :=Myarr_Var(Myarr_Var'First)'access;
begin
Put_Line(Integer'Image(Var.all));
var:=var+1;
Put_Line(Integer'Image(Var.all));-- why 1?
var:=var+8;
Put_Line(Integer'Image(Var.all));-- why -1 and some time different 4-7 digits no?
end Access_Pointer_Arithmetic;发布于 2015-01-11 22:15:31
您的Ada代码与此C完全等价:
#include <stdio.h>
int main()
{
int arr[5] = {2, 5, 7, 9, 0};
int *p = arr;
printf("%d\n", *p);
p += 1;
printf("%d\n", *p);
p += 8;
printf("%d\n", *p);
return 0;
}当它运行时,产生(在我的机器上)
2
5
32767您已经告诉编译器为5 ints (20字节)预留空间,在其中您已经放置了一些数据。编译器可以自由地使用数组结束后的空间来做它喜欢的任何事情;它当然不属于您,您不知道它的用途是什么:放手!
因此,当您增加指向数组中的第十个元素的指针时,如果您已经声明它至少有10个元素,那么您就是在寻址未定义的数据。您没有理由假设它是一个int;它可能是一个字符串的一部分,可能是一个double的中间,它可能是任何东西。在台式机上,它不太可能是一个内存位置,当它被读取时会导致机器着火;在运行您的烤面包机的微控制器中则不太可能。
通过指针写入几乎可以保证您的程序崩溃,立即或数千条指令后,当您将有真正的困难找到错误。
程序这种行为的Ada词是“错误的”;C词,我相信,是“未定义的”。
https://stackoverflow.com/questions/27879542
复制相似问题