I have read that sizeof operator in C is interpreted at compile time and since at compile time compiler knows the array size and its type,sizeof is abled to compute the number of bytes occupied by array.But how is sizeof working for the following code :
#include<stdio.h>
#include<string.h>
int main()
{
int n;
scanf("%d",&n);
int a[n];
int s=sizeof(a);
printf("%d",s);
return 0;
}
Here array size is not known at compile time,then how is it working properly ?
sizeof is always computed at compile time in C89. Since C99 and variable length arrays, it is computed at run time when a variable length array is part of the expression in the sizeof operand.
So deciding an array size at runtime is possible in modern C (>= C99) and code like the below is fine: int s; printf("Enter the array size: "); scanf("%d", &s); int a[s]; One obvious drawback of VLAs is that if s is quite big and the allocation of a could fail.
To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.
The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.
sizeof
is always computed at compile time in C89. Since C99 and variable length arrays, it is computed at run time when a variable length array is part of the expression in the sizeof
operand.
Same for the evaluation of the sizeof
operand: it is not evaluated in C89 but in C99 if the operand is of variable length array type it is evaluated. For example:
int n = 5; sizeof (int [n++]); // n is now 6
Since you are applying sizeof
to a variable-length array, whose size is not fully known at compile time, the compiler must generate code to do part of it at runtime.
gcc 4.6.3's high level optimizers convert the code you showed to
scanf ("%d", &n);
t12 = (long unsigned int) n;
t13 = t12 * 4;
__builtin_alloca (t13);
t16 = (unsigned int) t12;
t17 = t16 * 4;
s18 = (int) t17;
printf ("%d", s18);
Does that explain what is going on under the hood? (Don't be put off by the silly-looking number of temporary variables -- that's an artifact of the program being in static single assignment form at the point where I asked for an intermediate-code dump.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With