Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Does sizeof(Array) work

Tags:

arrays

c

How does c find at run time the size of array? where is the information about array size or bounds of array stored ?

like image 966
Kazoom Avatar asked Mar 22 '09 23:03

Kazoom


People also ask

How does sizeof know array size?

sizeof(type) gives you the number of bytes of the type you pass. Now if you pass array then the compiler knows that this is an array and number of elements in it and it just multiplies that many elements with the respective data-type size value. Again the sizeof(int) or sizeof(pointer) is platform dependent.

How does sizeof () work in C?

It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.

Why sizeof array is 8?

The size of any pointer is always 8 on your platform, so it's platform dependent. The sizeof operator doesn't care where the pointer is pointing to, it gives the size of the pointer, in the first case it just gives the size of the array, and that is not the same.

How does sizeof ARR )/ sizeof arr 0 ]) work?

If you have an array then sizeof(array) returns the number of bytes the array occupies. Since each element can take more than 1 byte of space, you have to divide the result with the size of one element ( sizeof(array[0]) ). This gives you number of elements in the array.


1 Answers

sizeof(array) is implemented entirely by the C compiler. By the time the program gets linked, what looks like a sizeof() call to you has been converted into a constant.

Example: when you compile this C code:

#include <stdlib.h> #include <stdio.h> int main(int argc, char** argv) {     int a[33];     printf("%d\n", sizeof(a)); } 

you get

    .file   "sz.c"     .section        .rodata .LC0:     .string "%d\n"     .text .globl main     .type   main, @function main:     leal    4(%esp), %ecx     andl    $-16, %esp     pushl   -4(%ecx)     pushl   %ebp     movl    %esp, %ebp     pushl   %ecx     subl    $164, %esp     movl    $132, 4(%esp)     movl    $.LC0, (%esp)     call    printf     addl    $164, %esp     popl    %ecx     popl    %ebp     leal    -4(%ecx), %esp     ret     .size   main, .-main     .ident  "GCC: (GNU) 4.1.2 (Gentoo 4.1.2 p1.1)"     .section        .note.GNU-stack,"",@progbits 

The $132 in the middle is the size of the array, 132 = 4 * 33. Notice that there's no call sizeof instruction - unlike printf, which is a real function.

like image 149
David Z Avatar answered Oct 06 '22 01:10

David Z