For any string "char name[10]="test"",is strlen(name)+1 always guaranteed to be same as sizeof(name)?

StackOverflow https://stackoverflow.com/questions/16534721

  •  29-05-2022
  •  | 
  •  

質問

For a string name[],can we use strlen(name)+1 and sizeof(name) interchangeably in our code without second thought?Aren't they same?I checked about it and found out even the return type for both is same,size_t.And after all sizeof calculates the size as a multiple of bytes and a character occupies one byte, while strlen() calculates the number of characters excluding the \0 due to which we have to add a 1 to equate it to the result of sizeof.

So unless the size of the character is something other than 1 byte,aren't the two interchangeable and same for all practical purposes?Like while allocating dynamic memory for example....

役に立ちましたか?

解決 2

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!

他のヒント

For a declared array like char name[10], sizeof(name) is the size of the entire array, regardless of what data is stored in it. strlen(name) returns the number of characters in the array before the first 0. Behavior of strlen is undefined if there aren't any zeros in the array.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top