0

int candidates[9][]最初の次元が既知 (9) で、2 番目の次元が実行に依存する配列が必要です。

配列を割り当てる方法は次のとおりであることがわかりました。

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

しかし、そのように使用して にアクセスしようとするとcandidates[i][j]、機能しません。正しいサイズの int[] を返すcandidate[i]関数で初期化しましたが、内容が間違っています。fun()candidate[i][j]

candidates[0] = fun();

どこが間違っているのかわかりません...助けてくれてありがとう:-)

4

3 に答える 3

1

*candidates[9]代わりにintを試してみてくださいint candidates[9][]。うまくいくはずです。

于 2013-01-14T10:03:46.407 に答える
0

int **candidates=0;を続けてみてくださいcandidates = new int *[9] ;

コード:

#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;
}
于 2013-01-14T10:38:16.183 に答える
0

STL のテンプレート クラスを試してみませんかvector...コードはよりすっきりと包括的です...

#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;
}

ポインターの配列を使用

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;

}

于 2013-01-14T10:22:01.257 に答える