Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

c - Why sizeof(param_array) is the size of pointer?

I want to get the length of an array, say int array[] = {1, 2, 3, 4}. I used sizeof to do that.

int length(int array[])
{
     return sizeof(array) / sizeof(int);
}

int main()
{
    int array[] = {1, 2, 3, 4};
    printf("%d
", length(array)); // print 1
    printf("%d
", sizeof(array) / sizeof(int)); // print 4
}

So, why the sizeof(array) in function length returns the pointer size of array? But in function main, it works.

And, how should I modify the length function to get an array's length?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A special C rule says that for function parameters, array types are adjusted to pointer types. That means:

int length(int array[]);

is equivalent to

int length(int *array);

So when you compute the sizeof the array you are actually computing the size of the pointer.

(C99, 6.7.5.3p7) "A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type", where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...