[OCLUG-devel] sizeof () works differently on char's, int's, etc.
Tim Thelin
tthelin at sbcglobal.net
Wed Jun 2 21:43:53 PDT 2004
James Colannino wrote:
> Hey everyone. I used the following to test how the sizeof() function
> measures arrays of various variable types:
>
> #include <stdio.h>
>
> char line[10];
> int integer[10];
> float floaty[10];
>
> int main()
>
> {
> printf ("\nCharacter: %d\n", sizeof(line));
> printf ("Integer: %d\n", sizeof(integer));
> printf ("Floating: %d\n\n", sizeof(floaty));
>
> return 0;
> }
>
> My output came out as the following:
>
> Character: 10
> Integer: 40
> Floating: 40
>
> So my question is this: why does the sizeof() function work with
> character arrays but not with numerical ones? Is the sizeof()
> function only intended to be used for characters and not for numbers?
> This has me very confused.
>
> James
James,
sizeof gives back the number of bytes of storage a particular entity
uses, not the number of elements in that entity.
So a typical use would be determining the size of a struct in bytes.
Along those lines, your results make sense, as your 10 ints would
consume 40 bytes of storage.
A way to get what you want, the number of elements of an array, could be
something more like:
#define GetNumberOfElements( array ) ( sizeof( array ) / sizeof(
array[0] ) )
That essentially gets the total bytes the array takes up, and divides it
by the size in bytes of a single element. The resuilt is the number of
elements.
Thanks,
Tim Thelin
More information about the OCLUG-devel
mailing list