Sum of two arrays

纵然是瞬间 提交于 2019-12-20 04:23:38

问题


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

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

|improve this question

回答1:


This:

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

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



回答2:


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

Your first lines in main should be:

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



回答3:


int sum[k] ;

k is a variable but the size of the array should be a constant.

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

But the function you wrote returns void which is clearly wrong.

Do I have to do it with pointers?

Yes.




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/5638445/sum-of-two-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!