两个数组的总和 [英] Sum of two arrays

查看:85
本文介绍了两个数组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该练习说:使一个具有两个int数组参数的函数,其大小为k.该函数应返回另一个数组(大小为k),其中每个元素都是相同位置的两个数组的总和.我写的东西,但是崩溃了,我必须使用指针吗?

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?

#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");
}

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

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

推荐答案

此:

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

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

causes undefined behaviour. The value of g is undefined upon initialisation, so therefore the length of a and b will be undefined.

您可能想要类似的东西:

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);

这篇关于两个数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆