简体   繁体   中英

Finding length of array and length of array with pointer pointing to it

int a[17];
size_t n = sizeof(a) / sizeof(int);

In C it is most common to find a length of an array like this and it is pretty clear. My question though is that the following wouldn't work:

int days[] = {1,2,3,4,5};
int *ptr = days;
size_t n = sizeof(ptr) / sizeof(int);

What I suppose is happening here is that ptr is just a normal 8-byte address pointing to the first element of the array, so it won't give us the real length of the array. But in the first example, sizeof(a), a is also just a pointer pointing to the first element of the array. So what is the difference here and why does one work but the other not?

What I suppose is happening here is that ptr is just a normal 8-byte address pointing to the first element of the array, so it won't give us the real length of the array

You are right.:)

But in the first example, sizeof(a), a is also just a pointer pointing to the first element of the array. So what is the difference here and why does one work but the other not?

Array designators are converted to pointers to their first elements in expressions except using them as operands of the operator sizeof or the operator & .

From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ''array of type'' is converted to an expression with type ''pointer to type'' that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

So in this expression

sizeof(a)

the array a is not converted to a pointer.

If you will write for example

sizeof( a + 0 )

then you will get the size of a pointer.

In the first case, you have an array. sizeof(a) give the number of bytes required to store it.

In the second case, you have a pointer. sizeof(ptr) gives the number of bytes required to store the pointer (Depends on architecture, usually 4 or 8).

The compiler knows the array size but doesn't know how many elements are pointer by a pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM