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?

2
  • Use %zu to print size_t values Commented Mar 30, 2016 at 10:04
  • Thank you for the answers everyone, I see the issue now. I'll keep trying and get back if I find a solution :) Commented Mar 30, 2016 at 10:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

"You'll have to pass the size of the array as a parameter." That's what the OP wants to calculate!
@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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.