数组的前一行元素也将更新

previous row element of array also getting updated

本文关键字:元素 一行 更新 数组      更新时间:2023-10-16

在这个程序中,我将整数从一个字符数组中分离出来,该数组由它们之间的空间组成

#include<iostream>     
#include<stdio.h>     
#include<conio.h>
using namespace std;
int main()
{
    int i = 0, t, l = 0, j, c, k, q = 0, num = 0;
    char ch[10][10];
    int ach[10][1];
    cout << "enter the number of test cases";
    cin >> t;
    for (i = 0; i < t; i++)
    {
        fflush(stdin);
        cin.getline(ch[i], 9);
    }
    for (i = 0; i < t; i++)
    {
        num = 0;
        for (j = 0; ch[i][j] != ''; j++) //calculating length   
        {
            l = j;
        }
        l = l + 1;
        for (j = 0; j < l; j++)
        {
            if (ch[i][j] == ' ') //finding the space     
                c = j;
        }
        for (k = 0; k < c; k++) //taking first integer out of char array    
        {
            q = ch[i][k] - 48;    //parsing char to int
            num = (num * 10) + q;
        }
        cout << "n previous row element " << ach[0][1] << "n"; //checking the value    
        ach[i][0] = num; // this statement is updating the previous row's last element of the array    
        cout << "n previous row element " << ach[0][1] << "n"; //checking the value    
        cout << ach[i][0];
        num = 0;
        q = 0;
        for (k = c + 1; k < l; k++) //taking second element out of char array     
        {
            q = ch[i][k] - 48;     //parsing char to int
            num = (num * 10) + q;
        }
        ach[i][1] = num;
        cout << ach[i][1];
    }
    for (i = 0; i < t; i++)
    {
        cout << "n" << ach[i][0] << "t" << ach[i][1] << "n"; //displaying the values       
    }
    getch();
    return 0;
}

我已经标记了出现故障的代码,它正在更新前一行的最后一个元素。请帮忙。

Oups您的代码并没有真正优化,除了cin.getline之外,主要是C。但您真正的问题是,对于int ach[10][1]ach是一个大小为10x1的2D数组,因此ach[i][1]可能不是您所期望的,因为您应该定义int ach[10][2]来安全地使用它。数组索引计算的规则给出了&(ach[i][1]) == &ach[0][0] + i*1 + 1,因此如果i为9,则您实际访问ach[i+1][0]时可能使用过去端数组访问权限。

此外,在第一次访问时,在不首先初始化的情况下使用ach[0][1]。

所以你的ach定义应该是:

int ach[10][2] = {0};