gpt4 book ai didi

c++ - 数组的前一行元素也得到更新

转载 作者:太空宇宙 更新时间:2023-11-04 13:28:21 24 4
gpt4 key购买 nike

in this program i am separating integers from a character array which consists of a space between them

#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] != '\0'; 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;
}

I have marked the code that is malfunctioning , it is updating the previous row's last element. please help.

最佳答案

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

此外,在第一次访问时,ach[0][1] 没有首先被初始化就被使用。

所以你的 ach 定义应该是:

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

关于c++ - 数组的前一行元素也得到更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32535045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com