You have so many errors in your code. First, you are not defining your arrays as arrays, but as single int values. You should define them correctly:
int *a, *b;
Second, you are not allocating your arrays. If you want to create them on runtime you will have to use malloc()
after you get the size for them:
a = (int*)malloc(sizeof(int) * n);
b = (int*)malloc(sizeof(int) * n);
Third, it is not necessary to pass your array values as reference, because you will not need to modify them:
printf("%d", inner_product(a, b, n));
Inside your inner_product()
function:
&(a + i)
and &(b + i)
won’t give you the memory position of the array item (because it depends on the memory block size). You should use &a[i]
and &b[i]
instead to get the array values.
Because your variables a
and b
are arrays, your inner product should be calculated this way:
for (i = 0; i < size; ++i)
sum += a[i] * b[i];
Tip: be sure to freeing your allocated a
and b
arrays by calling free(a)
and free(b)
after calling inner_product()
.
That’s it!
solved inner product function in C [closed]