PDA

View Full Version : Is it possible to have determine array size in runtime



MajidF
- 16th March 2016, 22:58
This is what the manual (http://melabs.com/resources/pbpmanual/) says about defining arrays:


4.5. Arrays


Variable arrays can be created in a similar manner to variables.


Label VAR Size[Number of elements]


Label is any identifier, excluding keywords, as described above. Size is BIT, BYTE or WORD. Number of elements is how many array locations is desired.

It is not clear if the Number of elements has to be a literal number or a variable can be used.

Can I do something like this?



READ 1, num_books ' how many nooks
books VAR BYTE[num_books] ' Define array for each book price

Heckler
- 17th March 2016, 14:26
I do not believe that you could demension an array in the middle of your code and have it be dynamic at runtime.
I believe that variables and arrays are defined and created by the compiler.

But I could be wrong?

Can you not just make your array sufficiently large to be ready for the largest number of books you expect to have?

pedja089
- 17th March 2016, 15:02
@Heckler
You are right, all variables are defined by compiler.

@MajidF
Number of elements must be a literal number or constant. Constants are just names that represents number.
So it must be a number like 15.
A var byte[15]
Or
NumberFifteen CON 15
A var byte[NumberFifteen]

Art
- 21st March 2016, 16:52
Hi, What you’re talking about is what malloc (memory allocate) in C does.
That’s intended for programs running under operating systems where other programs may be running,
and already consuming memory. So your program asks the system for a quantity of memory,
and a flag is returned if it was available.

I doubt it’s implemented in C for microcontrollers because the function would consume considerable
RAM and code space for many microcontrollers.

When you declare an array in PBP or RISC asm, all the compiler remembers is to reserve the next
memory spaces and mark the next variables in the locations following the array.


var byte array[20]
var byte value

In this case the variable “Value” will be permanently associated with RAM location 21,
and any time the array is used, the index is added to the array start location.


array[10] = 1

same as

(*array + 10) = 1

These numbers aren’t strictly true because PBP will put some of it’s own system variables before your array.

If there’s only one possible big array to deal with I don’t see a reason not to simply make it as large as you can afford.
If you don’t always use the maximum size of it, you can always mark the end with a normally unused character or sequence,
and search for that to find the current array size you’re using.