Object array, the difference between Java and C
I'm new to C. I'm porting a java project to C
Consider the following java code, where piece is a class representing chess pieces:
Piece[][] myPieces = new Piece[8][8];
It creates an array in which all entries are null
How can I achieve the same goal in C? I tried:
Piece* myPieces = new Piece[8][8];
But this creates an array in which all entries are initialized with the default constructor
thank you
Editor: I want C code to be efficient / elegant. I don't care and don't want to copy paste from Java to C. if necessary, I'm happy to modify the code structure a lot
Edit 2: the code is used for chess program. The size of the array will never change. Performance is very important
Solution
The answer depends on, because in C, as opposed to Java, you have different ownership semantics and object lifecycle management (both go hand in hand)
If you want to simulate an object similar to Java, you will write:
using PiecePtr = std::shared_ptr<Piece>; std::array<std::array<PiecePtr,8>,8> Pieces;
shared_ PTR has similar semantics to Java objects (pass it anywhere and guarantee its life cycle as long as there is a reference to it)
If you want to model the observed objects (that is, the array does not own them), you should write:
using PiecePtr = Piece*; std::array<std::array<PiecePtr,8> Pieces;
This ensures that when the pieces object is destroyed, the actual fragment itself remains in memory
If you want to model a unique object owned by the pieces array, you should use:
using PiecePtr = std::unique_ptr<Piece>; std::array<std::array<PiecePtr,实际的部件本身也会被销毁.