C语言 两个数组的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5638445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:22:45  来源:igfitidea点击:

Sum of two arrays

carrayssum

提问by captain

The exercise says "Make a function with parameters two int arrays and k which is their size. The function should return another array (size k) where every element of it is the sum of the two arrays of the same position. That's what I wrote, but it crashes. Do I have to do it with pointers?

练习说“创建一个函数,参数为两个 int 数组,k 是它们的大小。该函数应该返回另一个数组(大小为 k),其中每个元素都是相同位置的两个数组的总和。这就是我写的,但它崩溃了。我必须用指针来做吗?

#include <stdio.h>
#include <stdlib.h>

void sumarray(int k,int A[k],int B[k]){
   int sum[k],i;
   for(i=0;i<k;i++){                
   sum[i]=A[i]+B[i];
   printf("sum[%d]=%d\n",i,sum[i]);}

 }



main(){
   int i,g,a[g],b[g];
   printf("Give size of both arrays: ");
   scanf("%d",&g);
   for(i=0;i<g;i++){
      a[i]=rand();
      b[i]=rand();
   }
   sumarray(g,a,b);
   system("pause");
}

Example: If i have A={1,2,3,4} and B={4,3,2,1} the program will return C={5,5,5,5).

示例:如果我有 A={1,2,3,4} 和 B={4,3,2,1},程序将返回 C={5,5,5,5)。

回答by Oliver Charlesworth

This:

这个:

int i,g,a[g],b[g];

causes undefinedbehaviour. The value of gis undefined upon initialisation, so therefore the length of aand bwill be undefined.

导致未定义的行为。的值g在初始化未定义,所以因此的长度ab将是不确定的。

You probably want something like:

你可能想要这样的东西:

int i, g;
int *a;
int *b;  // Note: recommend declaring on separate lines, to avoid issues
scanf("%d", &g);
a = malloc(sizeof(*a) * g);
b = malloc(sizeof(*b) * g);
...
free(a);
free(b);

回答by The GiG

Its impossible to first do a[g]when dynamically getting g.

它不可能先做a[g]时动态获取g

Your first lines in main should be:

main 中的第一行应该是:

int i,g;
int *a,*b;
printf("Give size of both arrays: ");
scanf("%d",&g);
a = (int *)malloc(g*sizeof(int));
b = (int *)malloc(g*sizeof(int));

回答by Priyank

change the function summary signature (the definition part of the declaration) to this and try it out:

将函数摘要签名(声明的定义部分)改成这样,试试看:

void sumarray(int k,int* A,int* B){

void sumarray(int k,int* A,int* B){

回答by Mahesh

int sum[k] ;

kis a variable but the size of the array should be a constant.

k是一个变量,但数组的大小应该是一个常量。

The function should return another array (size k) ...

该函数应返回另一个数组(大小为 k)...

But the function you wrote returns voidwhich is clearly wrong.

但是您编写的函数返回void显然是错误的。

Do I have to do it with pointers?

我必须用指针来做吗?

Yes.

是的。

回答by Eric Conner

One issue is that you've attempted to declare dynamically sized arrays on the stack (e.g. a[g]). You need to declare pointers for each array and then dynamically allocate your variable sized array once you've read in the value of g.

一个问题是您试图在堆栈上声明动态大小的数组(例如a[g])。您需要为每个数组声明指针,然后在读取g.