質問

I would like to have a function, that when called creates a new stack, do some operations and then disposes the memory it used for stack. How can I do that?

I implemented my stack using an array:

 Type stack = record
 T :array[1..100] of integer;
 top:Integer
 end;

Edit: I want to use the stack in a function, and I want it to be local.

If I do

function A()
var S:stack
begin
    code();
end;

Will it dealocate the memory after the variable S once the funcion is done, or do I have to take care of it?

役に立ちましたか?

解決

If you use an array (static) implementation you do not need to 'dealocate' memory.

Read this: http://www.freepascal.org/docs-html/ref/refse19.html#x54-610004.1

When a variable is inside a function (procedure), it is deleted after exiting this function.

To implement the stack can be used static array or pointers ... similarly in C language.

simple (no error handling) implementation of stack using array.

program StackExample;

type TStack = record
  Items : array [1..5] of integer;
  Top: integer;
end;

var Stack : TStack;

function Stack_Init() : TStack;
var
  Stack : TStack;
begin
  Stack.Top := 1;
  Stack_Init := Stack;
end;

procedure Stack_Push(var Stack: TStack; Item : integer);
begin
  Stack.Items[Stack.Top] := Item;
  Stack.Top := Stack.Top + 1;
end;

function Stack_Pop(var Stack: TStack) : integer;
begin
  Stack.Top := Stack.Top - 1;
  Stack_Pop := Stack.Items[Stack.Top]
end;

{-----------MAIN------------}
begin
    Stack := Stack_Init();

    Stack_Push(Stack, 1);
    Stack_Push(Stack, 2);
    Stack_Push(Stack, 3);

    Writeln(Stack_Pop(Stack)); {get >> 3}
    Writeln(Stack_Pop(Stack)); {get >> 2}
    Writeln(Stack_Pop(Stack)); {get >> 1}
end

.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top