首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >2维数组分配,c++

2维数组分配,c++
EN

Stack Overflow用户
提问于 2013-01-14 18:01:04
回答 3查看 129关注 0票数 0

我希望有一个数组int candidates[9][],其中第一个维数是已知的(9),第二个维数取决于执行。

我发现分配数组的方法如下:

代码语言:javascript
复制
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]时,它不起作用。我使用函数fun()初始化candidate[i],该函数返回正确大小的int[],但是candidate[i][j]的内容是错误的。

代码语言:javascript
复制
candidates[0] = fun();

我不明白我哪里错了..。感谢您的帮助:-)

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-01-14 18:22:01

你为什么不试试STL...code的vector模板类,它更简洁,更全面……

代码语言:javascript
复制
#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;
}

具有指针数组的

代码语言:javascript
复制
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;

}

票数 0
EN

Stack Overflow用户

发布于 2013-01-14 18:03:46

尝试使用int *candidates[9]而不是int candidates[9][],它应该可以工作。

票数 1
EN

Stack Overflow用户

发布于 2013-01-14 18:38:16

先试试int **candidates=0;,然后再试试candidates = new int *[9] ;

代码:

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14316296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档