gpt4 book ai didi

ada - 我怎样才能增加一个访问类型,就好像它是一个 C 指针一样?

转载 作者:行者123 更新时间:2023-12-05 08:34:22 25 4
gpt4 key购买 nike

如何在 C 中递增访问类型的地址,如指针?我是 Ada 的新手...

procedure main is
type myarr is array(1..5)of integer; --creating array of 5 integer.
myarr_var:aliased myarr:=(2,5,7,9,0); --setting 5 values
type my_access is access all myarr; --creating access type (pointer)
var:my_access:=myarr_var'access; --holding address of 5 integer
begin;
-- since var holds the address of myarr_var now i want to increment
-- the address by adding 1 to print next value (5) as we do in c?

put((var+1).all); --???
-- i know this is bad but how to increment its base address of
-- var(pointer) so that it will point to next element 5?

end main;

最佳答案

实例化Interfaces.C.Pointers在 Ada 中进行 C 风格的指针运算。

最好用例子来解释:

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));
Increment(Var);
Put_Line(Integer'Image(Var.all));
Increment(Var);
Put_Line(Integer'Image(Var.all));
Increment(Var);
Put_Line(Integer'Image(Var.all));

Var := Var - 2;
Put_Line(Integer'Image(Var.all));
end Access_Pointer_Arithmetic;

运行它:

C:\Ada\Sandbox\access_pointer_arithmetic
2
5
7
9
5

该包提供了 ptrdiff_t 的单次递增/递减、加法和减法,以及指定终止符和定长元素数组的检索。

(注意跑到数组的末尾... :-)

关于ada - 我怎样才能增加一个访问类型,就好像它是一个 C 指针一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27825895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com