计算数组行中的总和

Calculate the sum in the rows of the array

本文关键字:数组 计算      更新时间:2023-10-16

我有一个二维数组a。我需要数组的元素被写入动态数组元素的元素中,记录数组A的行的计算和。使用指针显示动态数组元素。

const unsigned row = 3;
const unsigned col = 4;
int A[row][col];
std::cout << "Input A:n";
for (int index = 0; index < row; ++index) 
{
for (int j = 0; j < col; ++j) 
{
std::cout << "A[" << index << "][" << j << "]=";
std::cin >> A[index][j];
}
}
unsigned* array = new unsigned[row];
for (int index = 0; index < row; ++index)
{
for (int j = 0; j < col; ++j)
{
array[index] += A[index][j];
}
}

for (unsigned* index = array; *index; ++index) 
{
std::cout << *index << "n";
}

但遗憾的是,它不能正常工作。帮我弄清楚。

UPD:

unsigned* end = array + row + 1;
std::cout << "Array:n";
for (unsigned *ptr = array, index = 1; ptr <= end; ++ptr, ++index)
{
std::cout << *ptr << "t";
}

您从未初始化array,因此此行具有未定义的行为:

array[index] += A[index][j];

你可以简单地修复如果使用:

for (int index = 0; index < row; ++index) { 
array[index] = 0;
}

或者:

for (int index = 0; index < row; ++index) {
unsigned sum = 0;
for (int j = 0; j < col; ++j) { 
sum += A[index][j]; 
}
array[index] = sum;
}

最后一个输出也可以更改。您的版本读取超出了界限,因此又是一个未定义的行为。

for (int index = 0; index < row; ++index) { 
std::cout << array[index] << "n";
}