我希望有一个数组int candidates[9][],其中第一个维数是已知的(9),第二个维数取决于执行。
我发现分配数组的方法如下:
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]的内容是错误的。
candidates[0] = fun();我不明白我哪里错了..。感谢您的帮助:-)
发布于 2013-01-14 18:22:01
你为什么不试试STL...code的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-14 18:03:46
尝试使用int *candidates[9]而不是int candidates[9][],它应该可以工作。
发布于 2013-01-14 18:38:16
先试试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;
}https://stackoverflow.com/questions/14316296
复制相似问题