Jav
Jav

Reputation: 1607

2 dimensions array allocation, c++

I would like to have an array int candidates[9][] where the first dimension is known (9) and the second, depends on the execution.

I found that a method to allocate the array was the following:

int *candidates[9]; /* first allocation at declaration */
for(int i=0;i<9;i++) candidates[i] = new int[6]; /* allocation at execution */

but when I use it like that, and I try to access to candidates[i][j], it doesn't work. I initialize candidate[i] with a function fun() that return and int[] of the right size, but the content of candidate[i][j] is wrong.

candidates[0] = fun();

I don't understand where I am wrong... Thank you for your help :-)

Upvotes: 0

Views: 140

Answers (3)

rotating_image
rotating_image

Reputation: 3076

Why dont you try vector template class from STL...code is more neater and comprehensive...

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> arrayOfVecs[9];

    //use each array to put as many elements you want, each one different
    arrayOfVecs[0].push_back(1);
    arrayOfVecs[1].push_back(100);
    .
    .
    arrayOfVecs[1].push_back(22);
    arrayOfVecs[0].pop_back();
    arrayOfVecs[8].push_back(45);

    cout<<arrayOfVecs[1][0]<<endl;//prints 100

    return 0;
}

WITH ARRAY OF POINTERS

int main()
{
    int* arrayOfPtrs[9];

    for(int index = 0;index<9;index++)
    {
        int sizeOfArray = //determine the size of each array
        arrayOfPtrs[index] = new int[sizeOfArray];

        //initialize all to zero if you want or you can skip this loop
        for(int k=0;k<sizeOfArray;k++)
            arrayOfPtrs[index][k] = 0;

    }

    for(int index = 0;index<9;index++)
    {
        for(int k=0;k<6;k++)
            cout<<arrayOfPtrs[index][k]<<endl;
    }

    return 0;

}

Upvotes: 0

Software_Designer
Software_Designer

Reputation: 8587

Try int **candidates=0; followed by candidates = new int *[9] ;.

Code:

#include <iostream>
using namespace std;

int main(void)
{


    int **candidates=0;//[9]; /* first allocation at declaration */
    candidates = new int *[9] ;
    for(int i=0;i<9;i++) candidates[i] = new int ; /* allocation at execution */



    for(   i = 0 ; i < 9 ; i++ )
    {
        for( int  j = 0 ; j < 9 ; j++ )
        {

            candidates[i][j]=i*j;
            cout<<candidates[i][j]<<" ";
        }
        cout<<"\n";
    }



    cout<<" \nPress any key to continue\n";
    cin.ignore();
    cin.get();

   return 0;
}

Upvotes: 0

hmatar
hmatar

Reputation: 2419

Try int *candidates[9] instead of int candidates[9][] and it should work.

Upvotes: 1

Related Questions