Problems should be paid attention to using static arrays

zhaozj2021-02-16  41

One: Use a static array that should pay attention to:

1: CHAR static array is used in global variables and local variables.

You can prepare a simple test, at this time

Procedure tForm1.Button1Click (Sender: Tobject); var ARRAYCHAR: Array [1..100] of char; begin {point1} arraychar [1]: = 'a'; {Point2} arraychar [100]: = '6'; End; You can set a breakpoint at Point1, use the mouse observation, running to the case where Delphi is array ArrayChar allocates memory, you can see that Delphi is not all elements when you start allocating arrays, should It is a random allocation value. If you try to do this, if you don't understand this, you may feel very confused when you do some operations:,, for example, Procedure TFORM1.Button1Click (Sender: TOBJECT); VAR AG: Array [1 ..100] of char; I: integer; begin arraychar [1]: = 'a'; arraychar [99]: = '6'; for i: = low (arraychar) to high (arraychar) Do IF AG [i ] = '6' Then ShowMessage (INTTOSTR (I)); END; you want to find I's value is 99, but it is possible to get the wrong value, I have a small test, I am at this time The value obtained is 64, 94, and finally is 99. If it is slightly modified, as follows:

Procedure tForm1.Button1Click (Sender: TOBJECT); VAR ARRAYCHAR: ARRAYCHAR: ARRAY [1..100] of char; i: integer; j: integer; begin for j: = low (arraychar) to high (arraychar) do arraychar [J] : = # 0;

Arraychar [1]: = 'a'; arraychar [99]: = '6'; for i: = low-limited Do if arraychar [i] = '6' Then ShowMessage (INTTOSTR (i) ); End; At this time, there will be no previous situation. If you still use the same method to observe the dynamic array, it will find that a real dynamic array is in the beginning of initialization, it is already empty. If it is a static array of plastic, it should be set to 0 instead of # 0.

However, the above situation is that the static array is local variable, you can try to put it in front of the program, make it a global variable, you can observe again, you can find that this is, Delphi has automatically saved all the elements, In this case, you don't need to consider the initialization problem of static arrays.

For the array of strings, in both cases, it is already emptied when initialization, does not need you to do initialization

2: The cross-allmost problem of the dynamic array is as follows: Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT); var ARRAYDY: ARRAY OF CHAR; Begin SetLength (ArrayDy, 100); arraydy [0]: = 'a'; arraydy [1]: = 'b'; arraydy [99]: = 'c'; arraydy [100]: = 'd'; // error! Crossing ArrayDy [101]: = 'E'; // Error! Crossing SHOWMESSAGE (ArrayDy " ]) End; this is although array arraydy [100], ArrayDy [101] has been offline, but the program operates as usual. To make Delphi to make a prompt, you can open: Project / Options / Complier / Range Checking switch. QQ: 53997882

转载请注明原文地址:https://www.9cbs.com/read-26238.html

New Post(0)