-5

Array addition in C

Ive got a problem with this code, im trying to add up array1 with array2.

I enter the numbers for array2 by Command line parameters.

When i enter 10 numbers it is working but when i add less than 10 I get an Memory access error.

My question is now: how do i fill up the missing array fields with the number 0? For example : I enter 9 numbers and the 10th field should be 0.

jxh
  • 69,070
  • 8
  • 110
  • 193
frosty
  • 49
  • 1
  • 2
  • 12
  • 7
    Add your code in your question body. Don't link us to a picture of your code. – Tony Tannous Mar 16 '17 at 22:20
  • 5
    Welcome to Stack Overflow, you should post your code instead of images. – Iharob Al Asimi Mar 16 '17 at 22:21
  • 4
    The problem you have described and the question you ask are seemingly unrelated. The crash does not come from not initiaialising to zero. The problem is you access `argv` values that do not exist and hence accessing invalid memory. Modify your code to check `argc` first before using any of the `argv` values. – kaylum Mar 16 '17 at 22:25
  • 3
    And, please, post your code as text not as image. – Amin Negm-Awad Mar 16 '17 at 22:26
  • Possible duplicate: http://stackoverflow.com/q/5508110/315052 – jxh Mar 16 '17 at 22:34
  • 1
    `int array2[10] = {0}; for(i = 1; i < argc && i <= 10; ++i) array2[i-1] = atoi(argv[i]);` – BLUEPIXY Mar 16 '17 at 22:42

1 Answers1

2

You are not checking how many command line arguments are passed, and when you index into the command line argument array, you will get an out-of-bounds error.

In you addiren function, you should take advantage of the argc that is passed and used that in your for loop limit.

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

int addiren(int argc, char**argv){
    int array_one[10] = {0,1,1,2,3,5,8,13,21,35};
    int array_two[10] = {0}; //Quick way to set the array to all zeros
    int array_three[10] = {0};

    //Set array_two with your cmd-line args, notice the use of argc
    for(int i = 1; i<argc && i<=10; i++){
        array_two[i-1] = atoi(argv[i]);
    }

    //Add array_one with array_two to array_three
    for(int i = 0; i<10; i++){
        array_three[i] = array_one[i]+array_two[i];
    }

    //Return an int since that's what the function return type requires
    return 0;
}

Hope this helps!

Miket25
  • 1,895
  • 3
  • 15
  • 29