1

as part of a larger task I'm trying to print the length of an array in C, i.e how many elements are in an array. The array is an array of doubles, and I want to print a single integer which is how many doubles are in the array. I have this code:

int array_length( double array[] ) {
    double length = 0;
    length = sizeof(array) / sizeof(double);
    printf("%G", length);
    return 0;
}

and I call it in main like this:

int main( void ) {
    double test[] = {1.1,2.2,3.3,4.4,5.5};
    array_length(test);
    return 0;
}

however this returns the error:

error: ‘sizeof’ on array function parameter ‘array’ will return size of ‘double *’ [-Werror=sizeof-array-argument]

research has told me that

sizeof(array) / sizeof(double);

will give me the length of an array, and I am trying to using "%G" to allow me to print the double that this code returns.

I believe that "double*" means long double, so I tried changing "%G" to "%LG" and all uses of "double" to "long double", but that did not solve the problem. What is going on here?

CinCout
  • 9,486
  • 12
  • 49
  • 67
Isaac
  • 21
  • 1
  • 1
  • 6

2 Answers2

5

sizeof can only compute the size of an array if it's size is known in that scope. E.g.:

double array[10];
printf("%d", sizeof(array) / sizeof(double)); // prints 10

However:

void printSize(double array[]) {
    printf("%d", sizeof(array) / sizeof(double)); // doesn't print 10
}

Because here double array[] is just syntactic sugar for double* array.

Tamás Zahola
  • 9,271
  • 4
  • 34
  • 46
1

The array gets decayed into a pointer in the function argument and you thus can't find the size of the array from the function.

You'll have to pass the size of the array as a parameter.

blazs
  • 4,705
  • 24
  • 38
  • "You'll have to pass the size of the array as a parameter." That's what the OP wants to calculate! – CinCout Mar 30 '16 at 10:03
  • @HappyCoder I know, I'm just saying he'll have to provide the size somehow, because he won't be able to compute from the pointer. – blazs Mar 30 '16 at 10:08
  • Where C "sees" the array in its original array form (that is, in `main`()`), the array size is actually easy to calculate - and the OP seems to know how that is done. – tofro Mar 30 '16 at 10:08