> So I tried out this code, but it only works for odd number of elements.
Try your code with this array -
int a[] = {1,2,0,4,5,6,7,8,9};
^
|
3 replaced with 0
and you will find the output will be size=2
, why?
Because of the for loop condition - a[i] != '\0'
.
So, what's happening when for
loop condition hit - a[i] != '\0'
?
This '\0'
is integer character constant and its type is int
. It is same as 0
. When a[i]
is 0
, the condition becomes false
and loop exits.
In your program, none of the element of array a
has value 0
and for
loop keep on iterating as the condition results in true
for every element of array and your program end up accessing array beyond its size and this lead to undefined behaviour.
> Do all arrays end with NULL just like string.
The answer is NO. In C
language, neither array nor string end with NULL
, rather, strings are actually one-dimensional array of characters terminated by and including the first null character '\0'
.
To calculate size of array without using sizeof
, what you need is total number of bytes consumed by array and size (in bytes) of type of elements of array. Once you have this information, you can simply divide the total number of bytes by size of an element of array.
#include <stdio.h>
#include <stddef.h>
int main (void) {
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ptrdiff_t size = ((char *)(&a + 1) - (char *)&a) / ((char *)(a + 1) - (char *)a);
printf("size = %td\n", size);
return 0;
}
Output:
# ./a.out
size = 9
Additional:
'\0'
and NULL
are not same.