Sum of two arrays

前端 未结 5 1538
攒了一身酷
攒了一身酷 2021-01-23 14:50

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

相关标签:
5条回答
  • 2021-01-23 15:06

    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);
    
    0 讨论(0)
  • 2021-01-23 15:06

    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.

    0 讨论(0)
  • 2021-01-23 15:09

    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));
    
    0 讨论(0)
  • 2021-01-23 15:09

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

    0 讨论(0)
  • 2021-01-23 15:25
    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.

    0 讨论(0)
提交回复
热议问题