我的问题是添加元素。如果我再次尝试添加,它只是替换了最后添加的位置。添加时,它应该移动到下一个插槽/索引。
例如
0 1 2 3 4 5
0| a b c d e f
1| g h i j k l
2|
Add element:m
0 1 2 3 4 5
0| a b c d e f
1| g h i j k l
2| m
添加元素:n
0 1 2 3 4 5
0| a b c d e f
1| g h i j k l
2| m n
这是我的代码:
#include<iostream>
#include<string>
std::string myarray[3][6] = {{"a","b","c","d","e","f"},
{"g","h","i","j","k","l"},
{" "," "," "," "," "," "}};
void display();
using namespace std;
int main(){
while(true){
display();
char add;
int rows = 2;
int cols = 6;
cout<<"==========================================" <<endl;
cout<<"Add element: ";
cin>>add;
int size = rows*cols;
myarray[0][size] = add;
cout<<"Adding Successful!" <<endl;
size=size+1;
}
}
//display
void display(){
cout<<endl;
for(int z = 0; z<6; z++){
cout<<" "<<z;
}
cout<<endl;
for(int x = 0; x<3; x++){
cout<<x <<"|";
for(int y = 0; y<6; y++){
cout<<" " <<myarray[x][y] <<" ";
}
cout<<endl;
}
}
最佳答案
元素 myarray[0][size]
总是被分配一个新值,在每次迭代中都会计算一个新的 int size = rows*cols;
(尺寸
= 12)。而且您正在超出 ist 限制访问数组
如果不考虑任何其他问题,这可能会被修复:
int col=0;
while (col < 6) {
display();
char add;
cout<<"==========================================" <<endl;
cout<<"Add element: ";
cin>>add;
myarray[2][col] = add;
cout<<"Adding Successful!" <<endl;
++col;
}
关于c++ - 静态二维数组,添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49467697/