<gratuitous rant>
The string
is a lie. It is a typedef (alias) for the type char *
, which is not a string. A string is a sequence of characters followed by a 0-valued terminator. Strings are stored in arrays of char
(or wchar_t
for "wide" strings). A char *
may point to the first character in a string, or it may point to the first character in a sequence that is not a string, or it may point to a single character that is not part of any sequence. It is most definitely not a string. An object of type string
contains an address, not an actual string.
Its presence in the CS50.h header is a source of confusion and an active hinderance to you learning proper C string semantics. If you have a choice in the matter, don't use it.
</gratuitous rant>
As Jean-Francois pointed out, sizeof
returns the total number of bytes in an object; if you want to get the number of elements in the array, you must divide the total size of the array by the size of an individual element:
T arr[] = { /* some values of type T */ }; // for any type T
size_t count = sizeof arr / sizeof arr[0]; // or divide by sizeof *arr
Remember that sizeof
is an operator, not a function - if the operand is not a type name, it doesn't need to be surrounded by parentheses (although they don't hurt).
Note that this only works with array expressions, not with pointers. Remember that under most circumstances, an expression of array type will be converted ("decay") to an expression of pointer type, and the value of the expression will be the address of the first element1. If you tried to write a function that took an array as a parameter and returned the count, something like
size_t elt_count( int arr[] )
{
return sizeof arr / sizeof arr[0];
}
you won't get what you expect, because in this case arr
is a pointer, not an array2.
- Unless it is the operand of the
sizeof
or unary &
operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T
" will be converted ("decay") to an expression of type "pointer to T
" and the value of the expression will be the address of the first element of the array.
- In the context of a function parameter declaration,
T a[N]
and T a[]
are interpreted as T *a
; all three declare a
as a pointer to T
.