Curiousity with arrays (meaning, why is this happening? - Printable Version -Shoutbox (https://shoutbox.menthix.net) +-- Forum: MsgHelp Archive (/forumdisplay.php?fid=58) +--- Forum: Messenger Plus! for Live Messenger (/forumdisplay.php?fid=4) +---- Forum: Scripting (/forumdisplay.php?fid=39) +----- Thread: Curiousity with arrays (meaning, why is this happening? (/showthread.php?tid=80849) Curiousity with arrays (meaning, why is this happening? by MeEtc on 01-10-2008 at 05:13 PM I have the following code: code:gives the following output: code:Shouldn't the second line of letters be the same as the second? obviously, its not, and I'm trying to figure out why. RE: Curiousity with arrays (meaning, why is this happening? by Matti on 01-10-2008 at 05:39 PM
Let's try to understand what happens.
So, to make the data2 variable independent, you can use a nifty trick to make it immediately inherit the elements from the original array instead of making a reference to the first one: code:A small explanation here: the slice function returns a selected amount of elements from an array. You can specify a start and end position, but when you leave out the end parameter, it'll return the elements from the given start position to the end or the array. Result: all elements will be returned as a new array, and this returned array is saved as data2 variable. Oh note: you may want to remove the final semi-colon after "f" in your string, as you have an empty element at the end of your arrays now. Reference: http://www.sematopia.com/?p=12 RE: Curiousity with arrays (meaning, why is this happening? by Volv on 01-10-2008 at 05:39 PM
This is because of the following line: quote:I think Mattike already knows this but just expressed it ambiguously: it does not actually create a copy and then apply any changes made to the original to the new array, it only creates a reference to the original array. That is, that data2[] is essentially data[]. RE: Curiousity with arrays (meaning, why is this happening? by mynetx on 01-10-2008 at 07:15 PM In C++, this technics is called pointers because the variables contain pointers to the memory sectors where the data are stored. So, "data2 = data;" just copies the address of the array to the second. Obviously, both pointers point now to the same memory contents. |