dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: [RESOLVED] 2d Array problem

  1. #1
    Join Date
    Aug 2008
    Location
    Germany / NRW
    Posts
    37

    [RESOLVED] 2d Array problem

    Hi Folks,

    I've got a problem with the code below:

    Code:
    char** map;
    int iRows = 40;
    int iColumns = 50;
    
    //map = (char**)GlobalAlloc(GMEM_FIXED, iRows+1);
    map = (char**)new char[iRows];
    for(int i=0;i<iRows;i++)
    	//map[i] = (char*)GlobalAlloc(GMEM_FIXED, iColumns+1);
    	map[i] = (char*)new char(iColumns);
    
    
    for(int i=0;i<iRows;i++){
    	for(int j=0;j<iColumns;j++){
    		map[i][j] = 'X';
    	}
    }
    The problem is, that the last for-loop crashes on writting to the array after X loops.
    There is no problem in allocation, globalalloc and new both work fine it seems.

    what is wrong in that code?

  2. #2
    Join Date
    Jul 2002
    Posts
    2,543

    Re: 2d Array problem

    map = (char**)new char*[iRows];

  3. #3
    Join Date
    Sep 2004
    Location
    Holland (land of the dope)
    Posts
    4,123

    Re: 2d Array problem

    Code:
    map = (char**)new char[iRows];
    map is a char*, not a char**.

    Code:
    map = (char**)new char*[iRows];
    now it is.

  4. #4
    Join Date
    Aug 2008
    Location
    Germany / NRW
    Posts
    37

    Re: [RESOLVED] 2d Array problem

    one additional question...

    why does

    Code:
    for(int i=0;i<iRows;i++)
    	delete[] map[i];
    
    delete[] map;
    crashes ?
    how should I cleanup the memory insteat?

  5. #5
    Join Date
    Jul 2002
    Posts
    2,543

    Re: [RESOLVED] 2d Array problem

    Release code is OK, but there is one more problem:
    map[i] = (char*)new char(iColumns);

    Should be:
    map[i] = new char[iColumns];

    Don't use casting when this is not absolutely necessaty, this hides errors.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)