首先,你得到相同数字的原因在于你形成总和的地方。
在这个循环中
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = (*(ptr1)+*(ptr2));
}
你会发现 ptr1 和 ptr2 的内容总和,并且永远不会改变 - 这始终是前两个数字。
因此,我们可以通过在j 中进行索引来遍历数组,如下所示
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = (*(ptr1 + j) + *(ptr2 + j));
}
但是如果m!=n 会发生什么?你会离开数组的末端。
如果你把循环改成
for (int j = 0; j<m && j<n; j++)
{
*(sum + j) = (*(ptr1 + j) + *(ptr2 + j));
}
然后您会找到直到m 和n 中较小者的数字对的总和。
你将不得不对结果的显示做同样的事情
for (int j = 0; j<m && j<n; j++)
{
cout << *(sum + j) << endl;
}
但是,我相信您想要显示 n 数字,无论哪个更大,或者如果没有元素,则可能假设 0。另外,我注意到您已经 malloced 并且没有释放 - 也许使用 C++ 数组而不是 C 样式数组更好?稍后我会谈到这一点。
如果我们超出数组的末尾,让我们使用 C 方法并有一个0。
这可行,但可以整理 - cmets 内联一些重要的事情
#include<stdlib.h>
#include <algorithm> //for std::max
#include <iostream>
using namespace std;
int main()
{
int n, m;
int *ptr1, *ptr2, *sum;
cout << " enter the size of 1st and 2nd array : " << endl;
cin >> n >> m;
ptr1 = (int*)malloc(n * sizeof(int));
ptr2 = (int*)malloc(m * sizeof(int));
sum = (int*)malloc((std::max(n, m)) * sizeof(int));
// ^--- sum big enough for biggest "array"
// data entry as before - omitted for brevity
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = 0;
if (j < n)
*(sum + j) += *(ptr1 + j);
if (j < m)
*(sum + j) += *(ptr2 + j);
}
cout << " the sum is " << endl;
for (int j = 0; std::max(n, m); j++)//however big it is
{
cout << *(sum + j) << endl;
}
free(ptr1); //tidy up
free(ptr2);
free(sum);
}
我知道你说过你想使用 malloc,也许这是一种使用指针的做法,但请考虑使用 C++ 习惯用法(至少你不会忘记释放你用这种方式处理过的东西)。
让我们推动您的代码使用std::vector:
首先是包含和输入:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n, m;
vector<int> data1, data2, sum;
cout << " enter the size of 1st and 2nd array : " << endl;
cin >> n >> m;
cout << "enter 1st array element :";
for (int i = 0; i<n; i++)
{
int number;
cin >> number;
data1.push_back(number); //there is a neater way, but start simple
}
cout << "enter 2st array element :";
for (int i = 0; i<m; i++)
{
int number;
cin >> number;
data2.push_back(number);
}
这个post 展示了一种整理数据输入的方法。但是,让我们做一些简单的事情并得到总和:
for (int j = 0; j < std::max(m, n); j++)
{
int number = 0;
if (j < n)
number += data1[j];
if (j < m)
number += data2[j];
sum.push_back(number);
}
现在以 C++ 方式进行输出
cout << " the sum is " << endl;
for (auto item : sum)
{
cout << item << '\n';
}
}
最后,让我们简单地考虑一下总和。
如果您现在#include <iterator>,您可以使用算法将您的总和放入sum
std::transform(data1.begin(), data1.end(),
data2.begin(), std::back_inserter(sum), std::plus<int>());
但是,请注意这不会用零填充。您可以使向量大小相同,先用零填充,或者查找/发现压缩不同大小向量的方法。或者像我上面演示的那样在循环中坚持使用 ifs。
避免在 C++ 中使用 malloc。只是说说而已。