I assume you want to know how many elements are in the array, rather than the amount of storage consumed by the array.
Compare these declarations:
- char array1[] = {1, 2, 3, 4};
-
char array2[] = "1234";
-
const char *parray3 = "1234";
-
const char *parray4 = {1, 2, 3, 4};
The first declares array1 as an array of
4 char's: 1, 2, 3, 4. The number of elements in the array is intrinsic to the type of array1.
The second declares array2 as an array of
5 char's: '1', '2', '3', '4', 0. The number of elements in the array is intrinsic to the type of array2. (Reminder: '1' is the character "1", not the number "1".)
The third declares parray3 as a pointer to the start of an array of
5 char's: '1', '2', '3', '4', 0. This array is stored somewhere in memory, you really don't control where. The type of parray3 carries no information about the number of elements in the array.
I don't recall ever trying a declaration like the fourth one, but let's assume it is legal. If so, then it declares parray4 as a pointer to the start of an array of
4 char's: 1, 2, 3, 4. This array is stored somewhere in memory, you really don't control where. The type of parray4 carries no information about the number of elements in the array.
sizeof(array1) returns the amount of storage consumed by the array in char's. That's the same as the number of elements in a char array. What if you had defined array1 as an array of short's? Assume the size of a short is twice that of a char -- then sizeof(array1) would return twice the number of entries in the array -- the wrong answer. Can you think of a way to use sizeof() that will always give you the number of elements in an array regardless of the size of each element in the array? [Yes, there is a common C idiom for doing this!]
I can't think of any reliable/portable way to find the number of elements in the array pointed to by parray4.
Notice that array2 and the array pointed to by parray3 are strings. That means you can use strlen() to find the lengths of those strings. Notice that the length of a string is one less than the number of elements in the array (the terminating 0 isn't counted in the string length).
Notice that array1 and the array pointed to by parray4 are
NOT strings. That means that very bad things could happen if you tried to use strlen() on them. You might simply get a wrong answer; or your program might halt and dump core. Be afraid, be very afraid.
Here's one last wrinkle:
- char array5[10] = "1234";
This declares an array of 10 char's: '1', '2', '3', '4', 0, 0, 0, 0, 0, 0. In this case the number of elements in the array is
10, but the length of the string is 4.
Cheers,
Don