0

I am trying to a simple addition function that will take a number x from an array an and add a variable i to it, which is the iteration variable inside the for loop. Instead of adding each variable individually and producing the output of :

3, 2, 7

it produces values of

3, 5, 13.

#include <stdio.h>
int add(int x[], int y);
int main(void) {
    int i;
    int a[3] = {3, 1, 5};
    for(i=0; i<3; i++)
    {
        printf("%d \t", i);
        printf("%d, %d, equals %d \n", a[i], i,  add(a[i], i));
    }
    return 0;
}
int add(int x[], int y){
    return x+y;
}

3 Answers 3

6

Try

int add(int x, int y){
    return x+y;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@user3727944, if the answer worked for you then try to accept it.
[to OP] You're very right, but instead of adding only the modified code, try to explain a little about the reason for doing so. It helps everyone reading the answer :-)
2

In your function definition,

int add(int x[], int y){

int x[] expects an array to be passed as the argument. By calling that with

      add(a[i], i)

you're making multiple mistakes, like

  • passing an int value where int * is expected, so a wrong and implicit conversion from int to int * is talking place.
  • Inside add(), x is of type int *. So, by saying return x+y;, you're essentially again (wrongly) converting a pointer to int type.

Here, it seems, you need only one int variable. not an array. Change it (both declaration and definition) to

int add(int x, int y){

Suggestion: Turn up the compiler warnings and pay heed to them. For example, with the -Wall option enabled, you would have received a warning saying

warning: passing argument 1 of ‘add’ makes pointer from integer without a cast

printf("%d, %d, equals %d \n", a[i], i,  add(a[i], i));
                                             ^

and

expected int * but argument is of type int

int add(int x[], int y);

and,

warning: return makes integer from pointer without a cast

  return x+y;
  ^

Comments

1

You are using array as an argument. Please try below code:

#include <stdio.h>
int add(int x, int y);
int main(void) {
    int i;
    int a[3] = {3, 1, 5};
    for(i=0; i<3; i++)
    {
        printf("%d \t", i);
        printf("%d, %d, equals %d \n", a[i], i,  add(a[i], i));
    }
    return 0;
}
int add(int x, int y){
    return x+y;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.