2011-05-11 201 views
0

嗨,我想知道如何我可以將C++中的2d數組指針的內容複製到另一個位置並設置另一個指針,以便當我對複製的指針進行更改時,原始數據不會發生任何變化?C++複製指針

基本上它是一個棋盤上棋子的數組指針。所以它就像Piece * oldpointer = board[8][8]。現在我想複製這個指針中的所有內容,包括諸如getvalue(), getcolor()等這些在Pieces頭文件中的內容到另一個位置並設置一個指向它的指針,這樣我就可以在那裏執行操作並測試它,而不必影響這個原始數據?我讀了一個地方,我不得不使用allocate()但我不知道。請幫助

+0

解決方案是討論[這裏](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c/4810676#4810676),看看「轉換」(約3頁面向下)。 – fredoverflow 2011-05-11 11:38:45

回答

0

您可以通過在目的地分配內存複製,然後MEMCOPY

dest_pointer = (<<my type>>*) malloc(sizeof(<<my type>>); 
memcpy(dest_pointer, src_pointer, sizeof(<<my type>>); 

順便說一句,該方法不會被複制。他們不屬於一個對象。

+0

不要忘記包括。 – Lalaland 2011-05-11 04:17:19

+0

'memcpy'只適用於POD。 – fredoverflow 2011-05-11 11:40:06

1

在C++中,你可以定義二維數組類型,如下所示(你需要現代的C++編譯器):

#include <array> 
typedef std::array<std::array<Piece, 8>, 8> board_t; 

如果你的編譯器不支持std::array你可以用boost::array代替:

#include <boost/array.hpp> 
typedef boost::array<boost::array<Piece, 8>, 8> board_t; 

現在你可以使用上面的類型。我可以看到你需要複製到該指針指向對象:

board_t* oldpointer = new board_t; 

// do some with oldpointer 

// now make a copy of the instance of the object oldpointer points to 
// using copy-constructor 
board_t* newpointer = new board_t(*oldpointer); 
// now newpointer points to the newly created independent copy 

// do more 

// clean up 
delete oldpointer; 

// do more with newpointer 

// clean up 
delete newpointer; 
+0

還有std :: vector,它在任何地方都受支持。 – StilesCrisis 2011-05-11 05:23:53

+0

'std :: vector'動態分配內存。在國際象棋中,我知道有固定的棋盤大小,所以在'std :: vector'中不需要。 – 2011-05-11 07:22:51

+0

你是對的,但鑑於OP顯然是新手,將他指向高級或新引進的Boost或TR1等庫可能不是他學習的最佳方式。我懷疑矢量對於他的目的來說綽綽有餘,而且它在任何地方都有很好的文檔記錄。 – StilesCrisis 2011-07-26 00:11:59

1

由於您使用C++,爲什麼不定義你的作品類的拷貝構造函數?然後只是

Piece copied_piece(*board[8][8]); 

如果你的類是POD,你甚至應該能夠通過默認的拷貝構造函數來獲得。

+0

雖然董事會是他想要複製的東西...... 8-) 假設你有一個有8x8塊的板級,那麼你可以做這樣的事情:Board a; ...董事會b(a);數組應該隱藏在板子內部,並且所有的訪問都通過一個Piece get(int x,int y);來完成。 – 2012-01-02 05:56:18