Reputation: 15
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;
}
Upvotes: 0
Views: 100
Reputation: 134286
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
int
value where int *
is expected, so a wrong and implicit conversion from int
to int *
is talking place.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 typeint
int add(int x[], int y);
and,
warning: return makes integer from pointer without a cast
return x+y; ^
Upvotes: 2
Reputation: 29
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;
}
Upvotes: 1