Allocate an array with attributes

Share your advanced PureBasic knowledge/code with the community.
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Allocate an array with attributes

Post by Mistrel »

I found a really easy way to allocate a chunk of memory with attributes that can be transversed like an array.

The only down-side to this is that there is no bounds checking for the array elements and you have to remember to de-allocate the memory yourself.

This kind of memory allocation is useful for memory structures with blocks that are more easily transversed as an array. For example, an array of pixels has a height and width attribute. In this case you can have a structure ImageBlock that supports an arbitrary number of pixels which are allocated as memory during runtime.

Code: Select all

Structure MemBlock
	Attribute1.l
	Attribute2.l
	Block.l[0]
EndStructure

BlockSize=255
Mem=AllocateMemory(BlockSize*SizeOf(LONG)+SizeOf(MemBlock))

*MemBlock.MemBlock=Mem
*MemBlock\Attribute1=1
*MemBlock\Attribute2=2

For i=0 To 255-1
	Rnd=Random(255)
	*MemBlock\Block[i]=Rnd
	Debug Rnd
Next i