c - For any string "char name[10]="test"",is strlen(name)+1 always guaranteed to be same as sizeof(name)? -
for string name[],can use strlen(name)+1 , sizeof(name) interchangeably in our code without second thought?aren't same?i checked , found out return type both same,size_t.and after sizeof calculates size multiple of bytes , character occupies 1 byte, while strlen() calculates number of characters excluding \0 due have add 1 equate result of sizeof.
so unless size of character other 1 byte,aren't 2 interchangeable , same practical purposes?like while allocating dynamic memory example....
which book reading? sizeof operator tells how many bytes type (or in case, type of object) occupies. strlen function tells first '\0' character located, indicates end of string.
char foo[32] = "hello"; printf("sizeof foo: %zu\n", sizeof foo); printf("strlen(foo): %zu\n", strlen(foo)); sizeof foo 32 regardless of store in foo, can see strlen(foo) in fact 5, expect '\0' (nul-terminator) go.
in terms of dynamic allocation, can expect store return value of malloc in 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 case, sizeof foo sizeof (char *), because gives number of bytes in char * (pointer char). different strlen function because size of pointer char constant during runtime.
sizeof (char) always 1. that's required c standard. if find implementation isn't case, isn't c implementation.
perhaps book might explain this, why asked... there plenty of poor quality books. please answer question!
Comments
Post a Comment