Archived

This topic is now archived and is closed to further replies.

How to allocate DAM for a double subscript array

This topic is 5588 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Okay, I just got jammed up here. If I wanna allocate memory for a single subscript int array, I do this:
  

int *ptr;
ptr = new int[sizeOfMemory];
  
But what should I do if I wanna allocate memory for a "double-subscript" int array? I sincerely seek enlightenment from fellow C++ Pros. Thanks The road may be long, wind may be rough. But with a will at heart, all shall begone. ~savage chant

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
I think....

int **ptr;

can''t remember how to allocate though possibly:

ptr = new int[x][x];

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
I think....

int **ptr;

can't remember how to allocate though possibly:

ptr = new int[x][x];


nah, that won't work....

The problem with allocating double subscript stuff is that you have to know one of the dimensions first, ie this is legal :


    

// compiler will be happy with this ....

int (*pInt)[10];
pInt = new int[8][10];


// this will give you errors....

pInt = new int[8][8];


// because it expects 10 as the last index specified...




// this will also give error's :

int *pInt[10];
pInt = new int[8][10];


// because the data type is an array of 10 pointers to ints, not a multidimensional array pointer...



// though it would be legal to do this....

int **pp;
pp = new int*[10];

for(unsigned int i=0;i<10;i++)
pp[i] = new int[10];

unsigned int iCount =0;
for(unsigned int i=0;i<10;i++)
{
for(unsigned int j=0;j<10;j++)
pp[i][j] = iCount++;
}

for(unsigned int i=0;i<10;i++)
{
for(unsigned int j=0;j<10;j++)
std::cout << pp[i][j] << " ";
std::cout << std::endl;
}




[edited by - RobTheBloke on August 26, 2002 6:37:18 PM]

Share this post


Link to post
Share on other sites
You can dynamically allocate a double subscripted array by first dynamically allocating an array of int*. e.g.


  

int **ptr;

// allocate an array of int*

ptr = new int*[x];

// allocate an array (column) of int for each int* (row)

for( int i = 0; i < x; i++ )
ptr[i] = new int[y];

// note: you need to delete each ptr[i] and then ptr to free the memory





Hope that helps.

Never put passion above principle.

[edited by - StrongLikeBull81 on August 26, 2002 6:52:21 PM]

[edited by - StrongLikeBull81 on August 26, 2002 6:53:55 PM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Acknowledged and thank you all for sharing your great insights.
And thank goodness, it''s solved at last.

Share this post


Link to post
Share on other sites