Thread: help allocating 2d array w/ new

  1. #1
    Registered User Mr_Jack's Avatar
    Join Date
    Oct 2003

    help allocating 2d array w/ new

    WHY does this code not compile???:

    field_origin = new u8[field_size*6][field_size*10];
    Thanks for your help

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >WHY does this code not compile???
    Sadly, you can't do what you're trying to do. To simulate a two dimensional array, you need to create an array of pointers and then for each pointer, create an array of T:
    int **a = new int*[10];
    for ( int i = 0; i < 10; i++ )
      a[i] = new int[10];
    Or you could save yourself some calls to new:
    int *a = new int[10 * 10];
    But that isn't as handy when it comes to syntactic sugar and resizing.
    My best code is written with the delete key.

  3. #3
    Registered User manofsteel972's Avatar
    Join Date
    Mar 2004

    If you initialize the pointer to accept a 2 dimensional array it might work.

    At least this works in MS Visual C++ if you initialize the pointer to the same type as the 2 d array it will accept it.

    U8 (*field_origin)[field_size*10]; will create a pointer that is the same type as your array. field_size must be a constant though for it to work. I think U8 is equal to data type _int64 anyway here is the code i got to compile.

    	const int field_size=5;
    	_int64(*field_origin)[field_size*10]=new _int64[field_size*6][field_size*10];
    	int number=field_origin[0][0];
    	delete [] field_origin;
    Last edited by manofsteel972; 04-12-2004 at 08:45 AM.
    "Knowledge is proud that she knows so much; Wisdom is humble that she knows no more."
    -- Cowper

    Operating Systems=Slackware Linux 9.1,Windows 98/Xp
    Compilers=gcc 3.2.3, Visual C++ 6.0, DevC++(Mingw)

    You may teach a person from now until doom's day, but that person will only know what he learns himself.

    Now I know what doesn't work.

    A problem is understood by solving it, not by pondering it.

    For a bit of humor check out xkcd web comic

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. cannot print out my 2d array correctly! please help
    By dalearyous in forum C++ Programming
    Replies: 5
    Last Post: 04-10-2006, 02:07 AM
  2. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  3. Dynamically Allocating a 2D Array.
    By LightsOut06 in forum C Programming
    Replies: 17
    Last Post: 10-09-2005, 12:55 AM
  4. Read file in 2D array
    By Chook in forum C Programming
    Replies: 1
    Last Post: 05-08-2005, 12:39 PM
  5. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM