c++ - 静态二维数组,添加元素

标签 c++ arrays

我的问题是添加元素。如果我再次尝试添加,它只是替换了最后添加的位置。添加时,它应该移动到下一个插槽/索引。

例如

   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/

相关文章:

php - 如何将多维数组POST到PHP

php - WordPress:从数据库中的数组获取数据

c++ - 我是否正确使用 move 语义?会有什么好处?

c++ - Qt 捕获复选框的信号以执行操作

c++ - 在OpenCV中调用stereoRectify会导致异常: invalid frame pointer

arrays - Mongoose 查询 : Find an element inside an array

c++ - 在字符串中打印 HRESULT 符号(例如,E_FAIL 作为 CString)

C++ 多个枚举元素作为参数传递?

c - C 中的数组旋转

c++ - 动态指针是否设置为空