0

I'm trying to get size of an array in c and for some reason I'm getting a wrong answer for this popular method.

int innerprod(int *v, int *u)
{   
int n = sizeof(v)/sizeof(v[0]);
printf("%d\n",n);             // ouptut here is giving me '2' for a '3' size array          
double result = 0.0;
for (int i = 0; i < n; i++)
{
    result += v[i]*u[i];
    printf("%d\n",v[i]*u[i]);
}    
return result;
}

int main()
{
int V[3] = {3,4,-1};   //a 3 size array
int W[3] = {7,-2,3};
int x = innerprod(&V,&W);
printf("%d\n",x);
}
Crossfit_Jesus
  • 53
  • 4
  • 18
  • Ah! I guess there's no other solution than adding a parameter int for the size. – Crossfit_Jesus Mar 21 '19 at 23:27
  • @CrossfitJesus you could pass in an array pointer, a real one that is. – Fredrik Mar 21 '19 at 23:32
  • @Fredrik Yes I guess that's one way to go. Thanks! – Crossfit_Jesus Mar 22 '19 at 00:20
  • You cannot pass in arrays into functions, if you try, C passes an pointer to the array instead. Look at your `int innerprod(int *v, int *u)`: You correctly declared `v` as a pointer to an int. And consequently, `sizeof(v)` gives the size of the pointer, 8 on x86_64. `v[0] == *(v + 0)`, and therefore, `sizeof(v[0]) = sizeof(int)`, which again is 8 on x86_64. – Michael Beer Mar 22 '19 at 00:26

1 Answers1

1

Unfortunately arrays in C do not have boundary checking and have no way of knowing the length. Arrays are literally pointers into memory where your elements are lined up after another. You use the provided index to compute the memory location of the demanded element. Eg. adress of a[2] = a += 2. Accessing an elements outside the range of your array will most probably (this is also the best case) result in a segmentation fault. If not you will corrupt the memory of something which you should not be able to.

If you want this functionality you could use c++ with vectors from the <vector> library. Or you could build a struct which includes an entry for the size of the array.

Mr.Yellow
  • 692
  • 5
  • 15