Advertisement Jump to content
Sign in to follow this  
hnbmilk

Copying a 2d array in c++

This topic is 3683 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hello everybody, I'm having trouble passing a multidimensional array to a constructor of a class and saving that array in the class as a private member. I tried (where a2 is also Object* a2 [5][5]): Class::Class(Object* a1 [5][5]) { a2 = a1; } and Class::Class(Object* a1 [5][5]) { for(int i = 0; i <5; i++) for(int j = 0; j < 5; j++) a2[j] = a1[j]; } and various combinations. The second example compiles for me but when I do a a2[3][3] = new Object(); for example it doesnt modify the value that a1 points to. Is there any way to be able to recreate a 2d array so that a2 and a1 point to the same object? Thanks a lot for the help.

Share this post


Link to post
Share on other sites
Advertisement
Use a struct, arrays are not first class objects in C++:

struct Array
{
Object *data[5][5];
};

class Class
{
Array array;

public:
Class(const Array &array)
:
array(array)
{
}
};

Share this post


Link to post
Share on other sites
Quote:
but when I do a a2[3][3] = new Object(); for example it doesnt modify the value that a1 points to.


Of course not; each array has its own copy of the pointer value, and then you modify a2's copy of the pointer value (to point at a new object), while a1's copy still points to the same thing.

What are you really trying to do? C++ defaults to value semantics rather than reference semantics; this means (naive) copying is easy and sharing is hard. When you copy, you really make a copy, with its own identity.

Also, why would you have a fixed-sized grid of 5 by 5 arbitrary "objects"? What on earth does your program do?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!