【发布时间】:2012-01-03 14:56:03
【问题描述】:
我在 C 中有一个问题。这是问题:
开发一个将两个整数数组相加的 C 函数加法器。 ADDER应该只有两个参数,就是要相加的两个数组。第二个数组参数将保存退出时数组的总和。两个参数都应该通过引用传递。
编写一个 C 程序以调用 ADDER (A, A) 来测试 ADDER 函数,其中 A 是要添加到自身的数组。数组 A 可以是具有任何值的任何大小。编写、编译和执行程序。
解释程序的结果。
到目前为止,我已经以这种方式解决了它,并且效果很好:
#include <stdio.h>
// using namespace std;
const int SIZE = 5;
/* Adds two arrays and saves the result in b
* Assumes that b is larger than or equal to a in size
*/
void ADDER(int (&a)[SIZE], int (&b)[SIZE]) {
int aSize, bSize, i; /* variable declaration */
/* find out the sizes first */
aSize = sizeof (a) / sizeof (int);
bSize = sizeof (b) / sizeof (int);
/* add the values into b now */
for (i = 0; i < aSize; i++) {
b[i] = b[i] + a[i];
}
/* we have the sum at the end in b[] */
}
/* Test program for ADDER */
int main() {
int i; /* variable declaration */
int a[] = {1, 2, 3, 4, 5}; /* the first array */
/* add them now */
ADDER(a, a);
/* print results */
printf("\nThe sum of the two arrays is: ");
for (i = 0; i < SIZE; i++) {
printf("%d ", a[i]); /* print each element */
}
return 0;
}
问题是,我必须使用动态数组并在程序中使用 malloc 和 realloc 来动态计算数组的大小。我不希望指定数组大小和元素本身,而是希望程序要求用户输入并且用户输入数组并在那里确定大小。这一切都应该是动态的。我不知道这是怎么做到的。谁能帮帮我!谢谢!
我还必须解释如何将数组添加到自身,结果保存在“a”中,原始数组丢失被总和代替。我该如何解释?
【问题讨论】:
-
如果您希望数组是动态的,您必须修改
ADDER函数以接收一个或两个更多参数,即数组的大小。否则ADDER无法知道数组的大小。 -
可以修改
ADDER的签名吗?如果是这样,按照建议,将其更改为这些行void ADDER(int array1[], unsigned int size_of_array1, int array2[], unsigned int size_of_array2)上的内容并传递每个数组的大小 -
不,我无法更改 ADDER(a,a)
-
@JoachimPileborg ADDER 应该只有两个参数,我必须使用全局变量
标签: c arrays dynamic allocation