Click here to Skip to main content
15,897,315 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all

I am looking for Dynamic memory allocation in 2-D array. in C++
What exactly i Require is that I need 'N ' Number of Arrays, where in I would get value of 'N' at runtime only.

Each Array would be of size say ' Z ', wherein Z would be differnt for different array.

I thought of having 2-D array for the same, so that I can have all arays combined in one, But then the problem is that number of element is different in each array.

example is :

Suppose at Runtime user gives that i need to enter 4 types of data, so here, N=4

The
1st set has 10 items, so here z=10
2nd has 23 items, so here z=23
3rd has 12 items, so here z=12
4th has 90 items. so here z=90


This is what i require

Any pointer !!!
It would be a great help if i can have a code in C++ for the same.

Thanks in Advance
Posted
Updated 13-Feb-10 12:06pm
v2

You can use a vector of vectors for this.
Suppose the contents you want to store are ints then you would create such a vector as -
std::vector<std::vector<int>> vvInt;


To assign the first set of 10 values you could do this -
std::vector<int> vInt;

for (int i = 0; i < 10; ++i)
{
    vInt.push_back(i);
}

Now add this first set to the vector of vectors.
vvInt.push_back(vInt);

Similarly -
vInt.clear();

for (int i = 0; i < 23; ++i)
{
    vInt.push_back(i);
}

vvInt.push_back(vInt);
 
Share this answer
 
Thanks For the solution.

Even this worked for me

cout << " Enter the number of sets you want to test ";
cin >> size_x;

a= new int *[size_x];
/* a = new (size_x * sizeof(int *)); */

for (i = 0; i < size_x; i++)
{
cout << " Enter the number elemnets for group ";
cin >> size_y;

a[i]= new int [size_y +1];
/* a[i] = new (size_y * sizeof(int)); */

for (j = 1; j <= size_y; j++)
{
a[i][0]=size_y;

cout << " Enter the elements " ;
cin >> a[i][j] ;
}
}
 
Share this answer
 
v3
Here you have to take care of allocating and deallocating memory.
If this is not done properly you will have memory leaks.

A vector will internally take care of memory allocation for you guaranteeing no memory leaks.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900