# Thread: does C remember the no of elements in the Array??

1. ## does C remember the no of elements in the Array??

int a[99];

there are 99 (int)s memory allocated.

why we use sizeof( a ) , it can output 198 ?

why it knows ? where does it store the no of elements?

2. sizeof(a) gives you the size of the whole array, which is made up of sizeof(int) * 99.
It doesn't store the number of elements, but you can work it out with some simple maths:
sizeof(a) / sizeof(a[0])

But be careful if you pass "a" to a function, 'cos sizeof might not do as you expect.

3. O~~ thx..

my Eng. is poor..

i want to ask how C knows that the no. of element is 99 ??

and ,, can we get 99 in other method of sizeof(a)/sizeof(a[0]) ??

just want to know..

4. Code:
```#include <stdio.h>

int main(void)
{
int a[99];

printf ("sizeof(a)					  :%lu\n", sizeof(a));
printf ("sizeof(a[0])				   :%lu\n", sizeof(a[0]));
printf ("sizeof(int) (same as previous) :%lu\n", sizeof(int));
printf ("sizeof(a) / sizeof(a[0])	   :%lu\n", sizeof(a) / sizeof(a[0]));
printf ("396 / 4					    :%lu\n", 396 / 4);

return(0);
}

/*

My Output:

sizeof(a)					  :396
sizeof(a[0])				   :4
sizeof(int) (same as previous) :4
sizeof(a) / sizeof(a[0])	   :99
396 / 4					    :99

*/```
(excuse the poor layout, my browser seems to be doing strange things!)

5. the size of the type INT in your computer is 2 bytes. So the size an array of 99 elements , 2 bytes for each element , is 198.

and ,, can we get 99 in other method of sizeof(a)/sizeof(a[0]) ??
yes , try this :
Code:
`sizeof(a) / 2`
whereas 2 represent the size of int in your computer. Or more accurate\portable code :
Code:
`sizeof(a) / sizeof(int)`

hammer used "sizeof(a) / sizeof(a[0])" where 'sizeof(a[0])' means the size of one element (the 0 can be replaced with any number within the array range), and since its an INT array , the sizeof(a[0]) would return 2 in your computer and 4 in hammer's , because an INT is either 2 or 4 bytes big (depends on how the computer treats it).

hope this clears things up

6. But again, as Hammer stated, this method will not work unless you are in the original declaring scope of the array:
Code:
```void foo( int bar[99] )
{
printf("The size of the array in foo: %d\n", sizeof( bar ) / sizeof( bar[0] ) );
}

int main( void )
{
int baz[99];
printf("The size of the array in declared scope: %d\n",
sizeof( baz ) / sizeof( baz[0] ) );

foo( baz );

return 0;
}```
Thus, you can only get the size of an array in the scope in which it was declared.

Quzah.

7. char a[99];

sizeof(a); // <<--- How does "sizeof" work to know the no. of elements is 99 ?? I am wondering if there is a place in the memory to store the 99 ??

8. sizeof is a compile time operation. So when the compiler sees
Code:
`char a[99];`
it adds a to its symbol table and keeps track of it's type and its size.

9. OK , i understood now. thank .'