2

so i was just playing around with the code to find array length.... the orignal code was:

#include<stdio.h>

int main()
{   int al;
    int a[] = {1,2,3,4,5};
    al= sizeof(a) / sizeof(a[0]);
    printf("%d",al);
    return 0;
}

which gave me the output of:

5

but when i changed the expression to:

al= sizeof(&a[0]) / sizeof(a[0]);

it gave me the output of

2

if a is the same as &a[0] ...then why does this happen? Also, if put &a in place of &a[0] the answer is also 2.

1
  • 3
    if "a" is the same as "&a[0]" ...then why does this happen? Because a is not the same as &a[0]. Commented Nov 18, 2018 at 19:06

1 Answer 1

8

No, they differ in type.

For context of sizeof operator, a is of type int [5], but , &a[0] is of type int *. They are indeed of different size. Following the same analogy, &a is of type int (*)[5] - basically, a pointer.

So, for the expression

al= sizeof(a) / sizeof(a[0]);

is the same as

al= sizeof( int [5]) / sizeof(int);

which gives you 5. On the other hand,

al= sizeof(&a[0]) / sizeof(a[0]);

is the same as

al= sizeof(int *) / sizeof(int);

now, it appears, in your platform, sizeof(int *) is 8 and sizeof(int) is 4, so you get to see a result of 2.

Remember, in some cases, array type decays to a pointer to the first element of the array, but one of the exceptional cases where is does not, is when the array is used as the operand of sizeof operator.

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

6 Comments

can you explain in a bit more detail please? dumb it down for me...i am new to programming
@SouravGhosh just saw it
@AnasAziz sizeof() is not a function, it's preprocessed at compile time. At some point all arrays are handled as pointers, and they implicitly convert into pointers aswell, but only at compile time the compiler knows that is an array and what is it's real size. sizeof() cannot tell the size of an array just from it's pointer, and that's why it will give you the size of the pointer instead (8, for 64-bit pointers).
@Havenard sizeof is not part of what is usually called "the preprocessor"; you can't use it in preprocessor arithmetic. Also it is not true that "At some point all arrays are handled as pointers", that sort of bogus statement is what leads to beginners being confused about this issue in the first place
@M.M Please clarify why it's bogus. Also I never said the preprocessor was responsible for preprocessing sizeof(), I simply used the to preprocess verb for lack of a better one and explicitly attributed the action to the compiler.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.