Pascal:指向未知大小的数组?

时间:2015-05-23 07:18:23

标签: arrays pointers dynamic pascal lazarus

此刻我与帕斯卡(使用拉撒路)挣扎....

我正在尝试设置一个基于const记录来填充组合框的系统。这些是指向字符串数组的指针。我的想法是,在运行时我可以通过选择不同的记录来修改UI。

我的问题是,如果我在记录定义中定义字符串数组的大小,这一切都有效。但我不想这样做,因为它会有所不同。我试图使用动态数组,但有例外。

我会感激地收到关于我做错事的指针(!);)

希望这段代码片段能更好地解释我在做什么.....

type
  // definition of the record used for setting the combo box
  TComboItemsTextArray = array[0..10] of string[25]; // this works but I don't want to define the arrray size here.....
  // TComboItemsTextArray = array of string;         // this alternative gives an exception.

  TQDef = record
    ......
    Min : Integer;            
    Max : Integer;            
    ComboItemTextArray : ^TComboItemsTextArray;  
    ........
  end;

const
  // example text array for a specific combo setup
  Names : array[1..5] of string[25] =
  (
    'Name 1',
    'Name 2',
    'Name 3',
    'Name 4',
    'Name 5'
  );

  // specific combo box setup record
  QDef1 : TQDef =
  ( 
    ......
    Min:1;
    Max:5;
    ComboItemTextArray:@Names;
    .....
  );


var
  Q : TQDef;  
  I : Integer;
  ...
begin

  // set the question to be used
  Q := Qdef1;


  // use array to setup combo box
  for I := Q.Min to Q.Max do
    QCombo.Items.Add(Q.ComboItemTextArray^[I]);

end;

2 个答案:

答案 0 :(得分:0)

在FPC和D2009 +中,指向X的指针可以作为数组过度索引。但是这些黑客并不是非常好。

从各种未链接的阵列创建数据结构运行时是最简单的选择。更先进的是进入资源的方向。

答案 1 :(得分:0)

你的问题并没有说明这一点,但我忘了你试图动态定义数组的大小。这可以这样做:

type
  // definition of the record used for setting the combo box
  TComboItemsTextArray = array[0..10] of string[25]; // this works but I don't want to define the arrray size here.....
  // TComboItemsTextArray = array of string;         // this alternative gives an exception.

      TQDef = record
        ......
        Min : Integer;            
        Max : Integer;            
        ComboItemTextArray : ^TComboItemsTextArray;  
        ........
      end;

    ...

        var
          Q : TQDef;
          length : integer;

          length := 20; // Arbitrary length...
          SetLength(Q.ComboItemTextArray, length)
相关问题