Arrays ALWAYS contiguous in memory?

Everything else that doesn't fall into one of the other PB categories.
Amiga5k
Enthusiast
Enthusiast
Posts: 329
Joined: Fri Apr 25, 2003 8:57 pm

Arrays ALWAYS contiguous in memory?

Post by Amiga5k »

I know linked lists can theoretically be all over the place in memory (even though their internal pointers point to the correct next and previous link), but can arrays always be expected to be contiguous in memory? For example, is it safe to do this?

Code: Select all

Structure TTest
   a.l
   b.l
EndStructure
Global Dim arr1.TTest(5)
; ...fill arr1
Global Dim arr2.TTest(5)
CopyMemory(@arr1(0),@arr2(0),SizeOf(TTest) * 6)
...or should all of the array elements be copied one at a time?

Thanks
Russell
*** Diapers and politicians need to be changed...for the same reason! ***
*** Make every vote equal: Abolish the Electoral College ***
*** www.au.org ***
User avatar
Kaeru Gaman
Addict
Addict
Posts: 4826
Joined: Sun Mar 19, 2006 1:57 pm
Location: Germany

Post by Kaeru Gaman »

afaik, yes.

never heard the converse...

even ReDim or again Dim is safe.
oh... and have a nice day.
User avatar
pdwyer
Addict
Addict
Posts: 2813
Joined: Tue May 08, 2007 1:27 pm
Location: Chiba, Japan

Post by pdwyer »

I'm screwed if they are not! :o
Paul Dwyer

“In nature, it’s not the strongest nor the most intelligent who survives. It’s the most adaptable to change” - Charles Darwin
“If you can't explain it to a six-year old you really don't understand it yourself.” - Albert Einstein
Amiga5k
Enthusiast
Enthusiast
Posts: 329
Joined: Fri Apr 25, 2003 8:57 pm

Post by Amiga5k »

lol :D (Me, too, as I am asking this question after having used this trick many, many times already...). Saving an array of structures to disk is very convenient using this method:

Code: Select all

Structure TTest
   x.l
   y.l
   author.s{40}
   _data.l[1000]
EndStructure

Global Dim level.TTest(10)
; Fill level array with data...

OpenFile(0,"Test")
WriteData(0,@level(0),SizeOf(level) * 11)
CloseFile(0)
Sure beats field by field copying!

Russell
[Edit: Added _ to the data.l long field in TTest. Also, in reality I would of course check to make sure the file had been opened successfully first... But this is just an example ;)]
*** Diapers and politicians need to be changed...for the same reason! ***
*** Make every vote equal: Abolish the Electoral College ***
*** www.au.org ***
User avatar
Kaeru Gaman
Addict
Addict
Posts: 4826
Joined: Sun Mar 19, 2006 1:57 pm
Location: Germany

Post by Kaeru Gaman »

sure, it's much faster than element by element.
my example is 1. older 2. should show the concept of dynamic mapsizes.

you can use WriteData / ReadData with my example, too.

additionally, you can put a sole pointer into the structure and
allocate the Mem for the Array on-the-fly after reading the dimensions.
oh... and have a nice day.
Post Reply