In last Monday's lecture we saw both the
sizeof()
and
strlen()
functions when discussing arrays and, in particular, arrays of characters which we treated as strings. The two functions serve different roles and, so, shouldn't be confused.
The function
sizeof()
is not really a function at all - that is, it's not a named sequence of statements that are executed when our program runs. In fact
sizeof()
is a syntactic sequence recognised by the C compile - at compile time. The single parameter to
sizeof()
may be a datatype, or the name of a variable, and the compiler generates code involving the number of bytes required to store that datatype or variable. This is done at *compile-time*.
For example, the
printf()
call in
char char_array[100];
int int_array[100];
double x;
printf("%lubytes %lubytes %lubytes\n",
sizeof(char_array), sizeof(int_array), sizeof(x) );
may produce
100bytes 400bytes 8bytes
, depending on the hardware/architecture being used.
In contrast, the function
strlen()
determines the number of bytes from the beginning (address) of its parameter to the first NULL-byte found. The function is called at *run-time*, when our program is executed. For example, consider:
char string[100];
string[0] = '\0';
strcpy(string, "budgie"); // copy a string constant into a char array
strcpy(string, "boo");
While the value of
sizeof(string)
is *always* 100, but the value of
strlen(string)
is initially 0, then 6, then 3.