Which book are you reading? sizeof
is an operator that tells you how many bytes a type (or in your case, the type of an object) occupies. strlen
is a function that tells you where the first '\0'
character is located, which indicates the end of the string.
char foo[32] = "hello";
printf("sizeof foo: %zu\n", sizeof foo);
printf("strlen(foo): %zu\n", strlen(foo));
sizeof foo
is 32 regardless of what you store in foo
, but as you can see strlen(foo)
is in fact 5
, where you would expect the '\0'
(NUL-terminator) to go.
In terms of dynamic allocation, you can expect to store the return value of malloc
in a pointer.
char *foo = malloc(32);
strcpy(foo, "hello");
printf("sizeof foo: %zu\n", sizeof foo);
printf("sizeof (char *): %zu\n", sizeof (char *));
printf("strlen(foo): %zu\n", strlen(foo));
In this case, sizeof foo
is sizeof (char *)
, because it gives you the number of bytes in a char *
(pointer to char). This is very different to the strlen
function because the size of a pointer to char is constant during runtime.
sizeof (char)
is always 1. That's required by the C standard. If you find an implementation where that isn't the case, then it isn't a C implementation.
Perhaps your book might explain this, which is why I asked... but there are plenty of poor quality books. Please do answer that question!