gpt4 book ai didi

pointers - Ada 数组访问 : Pointer to a specific item within the array, 该位置根据输入参数动态变化。

转载 作者:行者123 更新时间:2023-12-03 06:30:36 25 4
gpt4 key购买 nike

我在 Ada95 中工作,但我很难找出指针。

我的代码如下所示:

type vector is array (1 .. 3) of integer;   
type vector_access is access vector;

my_vec : vector;

procedure test is
pointer : vector_access := my_vec'access;
begin
...
end;

这对指针定义的编译失败,说

"The prefix to 'ACCESS must be either an aliased view of an object or denote a subprogram with a non-intrinsic calling convention"

如果我将向量本身的定义更改为:

my_vec : aliased vector  

它现在返回编译器错误:

"The expected type for X'ACCESS, where X denotes and aliased view of an object, must be a general acces type"

归根结底,我真正需要的是指向数组中特定项目的指针,该位置根据输入参数是动态的。谁能指出我正确的方向?

最佳答案

如果您使用 GNAT,“必须是通用访问类型”后面的错误消息应该已经为您提供了解决方案:

add "all" to type "vector_access" defined at line ...

这样你最终会得到:

type Vector_Access is access all Vector;

使用“all”来指定通用访问类型与 Ada 中的动态内存分配池有关。如果您不关心动态内存分配池,则不必担心,只需在访问类型定义中包含“all”即可。

我不确定这是否是您最终要寻找的内容的一部分,但您知道在大多数情况下 Ada 的访问(指针)类型用于处理动态分配的内存,对吧?

因此,您可以动态分配它,而不是将 my_vec 指向别名变量:

Pointer_2_Dynamic : vector_access := new Vector;

通过这种方式,您可以在运行时动态分配所需的对象,并轻松处理可变大小的对象(尽管您需要不同的向量定义来实现这一点:

type Dynamic_Vector is array (Natural range <>) of Integer;
type Dynamic_Vector_Access is access Dynamic_Vector;

N : Natural := 10; -- Variable here, but could be a subprogram parameter.
Dyn_Vector : Dynamic_Vector_Access := new Dynamic_Vector(1..N);

关于pointers - Ada 数组访问 : Pointer to a specific item within the array, 该位置根据输入参数动态变化。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3780962/

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