none
How to copy one char* array into another one?

    Question

  • I am having a lot of problems with this. Basically I am passing a char* array to a function and I want to copy it into another one. Here is the Relevant code:

     

    In TileLinker.h:

     

     

    class TileLinker
    
    	{
    
    		int tilesLinked;		
    
    		int arrSize;
    
    		char** tiles;
    
    	public:	
    
    		TileLinker();
    
    		TileLinker(char* newTiles[]);
    
    	.......................
    
    	}
    

     

     

    In TileLinker.cpp:

     

    TileLinker::TileLinker(char* newTiles[])
    
    	{
    
    		arrSize = 0;
    
    		tilesLinked = 0;
    
    		tiles = new char* [sizeof(newTiles)];
    
    		tiles = newTiles;
    
    		do
    
    		{
    
    			*tiles++ = *newTiles++;
    
    		} while (*newTiles != 0);
    
    	}
    
    int _tmain(int argc, _TCHAR* argv[])
    {
       char *tiles1[] = {
    	"11",   // 1
    	"23",
    	"",
    	"44",   // 2
    	"11",
    	"",
    	"16",   // 3
    	"36",
    	"",
    	"51",   // 4
    	"71",
    	"",
    	"46",   // 5
    	"26",
    	"",
    	"14",   // 6
    	"68",
    	0};
    
       TileLinker* myTileLinker = new TileLinker(tiles1);
    }
    

    So basically what I want to do is copy newTiles into tiles. The way I am trying to do it with:

    *tiles++ = *newTiles++;
    
    is not working. What is the correct way to do this?

     

     

     

    Sunday, August 29, 2010 9:40 PM

Answers

  • 		tiles = new char* [sizeof(newTiles)];
    
    

    The above sizeof doesn't give you the size of the array. It just gives you the size of a pointer, which is 4 bytes (32 bits) for 32-bit applications and 8 bytes (64 bits) for 64-bit applications. If want the actual size of the array, you have to take it as a paramenter.

    		tiles = newTiles;
    
    

    This assignment doesn't actually copy the array of strings. It just assigns the memory address newTiles into tiles. And since tiles previously pointed to heap memory, you have a memory leak.

    What I would recommend is to avoid using raw arrays and null-terminated strings, and instead use array and string classes like the STL's std::string/std::wstring and std::vector or MFC's CString and CArray.

    Then, TileLinker would look like this:

    class TileLinker
    {
      std::vector<std::string> m_tiles;
    
    public:
      TileLinker()
      {
      }
    
      TileLinker(const std::vector<std::string>& newTiles) : m_tiles(newTiles)
      {
      }
    
      ...
    };
    
    Sunday, August 29, 2010 10:43 PM