C sizeof a passed array [duplicate]

2018-12-31 10:09发布

Possible Duplicate:
How to find the sizeof( a pointer pointing to an array )

I understand that the sizeof operator is evaluated and replaced with a constant at compile time. Given that, how can a function, being passed different arrays at different points in a program, have it's size computed? I can pass it as a parameter to the function, but I'd rather not have to add another parameter if I don't absolutely have to.

Here's an example to illustrate what I'm asking:

#include <stdio.h>
#include <stdlib.h>

#define SIZEOF(a) ( sizeof a / sizeof a[0] )


void printarray( double x[], int );

int main()
{
        double array1[ 100 ];


        printf( "The size of array1 = %ld.\n", SIZEOF( array1 ));
        printf( "The size of array1 = %ld.\n", sizeof array1 );
        printf( "The size of array1[0] = %ld.\n\n", sizeof array1[0] );

        printarray( array1, SIZEOF( array1 ) );

        return EXIT_SUCCESS;
}


void printarray( double p[], int s )
{
        int i;


        // THIS IS WHAT DOESN"T WORK, SO AS A CONSEQUENCE, I PASS THE 
        // SIZE IN AS A SECOND PARAMETER, WHICH I'D RATHER NOT DO.
        printf( "The size of p calculated = %ld.\n", SIZEOF( p ));
        printf( "The size of p = %ld.\n", sizeof p );
        printf( "The size of p[0] = %ld.\n", sizeof p[0] );

        for( i = 0; i < s; i++ )
                printf( "Eelement %d = %lf.\n", i, p[i] );

        return;
}

7条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 10:35

The problem is that your function doesn't receive an array value; it receives a pointer value.

Except when it is the operand of the sizeof or unary & operators, or it is a string literal being used to initialize another array in a declaration, an expression of type "array of T" will be converted to type "pointer to T" and its value will be the address of the first element of the array.

Thus, when you call printarray, the type of array1 is implicitly converted from "100-element array of double" to "pointer to double." Thus, the type of the parameter p is double *, not double [100].

In the context of a function parameter declaration, T a[] is identical to T *a.

This is why you have to pass the array size separately;

查看更多
登录 后发表回答