-1

When I print strlen(str) and sizeof() Here is one char array:

const char *str = "Geeksforgeeks"; 

When I print strlen(str) and sizeof(str) it gives output as :

cout<<strlen(str)<<endl;
cout<<sizeof(str)<<endl;

output:

strlen(str): 13
sizeof(str): 8
  • which should not be the case; sizeof() should return 14 because of extra null character?
  • I tried this for smaller strings and sizeof() value doesn't change, still 8 ?
  • 2
    The return value of `sizeof` depends only on the type of the expression, and nothing else. The type of `str` is `const char *`, and the size of a pointer doesn't depend on the data it points to. – HolyBlackCat Jul 16 '20 at 22:25
  • 1
    The size of a container does not depend on the container's contents. Changing the value of a variable doesn't change its size. – David Schwartz Jul 16 '20 at 22:26
  • https://stackoverflow.com/questions/17298172/how-does-sizeof-work-for-char-pointer-variables. The strlen returns the length of string, where as sizeof() is the size of char ptr. – TippuR Jul 16 '20 at 22:27
  • David Schwartz hints at something really important about pointers in his comment: A pointer is just another data type, one where the value just happens to be a location in storage. Knowing this will help you understand why pointers sometimes need to be passed by reference. – user4581301 Jul 16 '20 at 22:30
  • *Here is one char array:* -- No, that is a string-literal -- pointers are not arrays. Change that to `char str[] = "Geeksforgeeks";` and you may see the result you're looking for. – PaulMcKenzie Jul 16 '20 at 22:31

1 Answers1

4

Why is sizeof(str) is equal to 8

Because the type of str is const char * i.e. pointer to const char, and the size of pointers on your system happens to be 8 bytes.

when it should be equal to strlen(str)+1 …

No it shouldn't, because that number is not the size of the type which is what the sizeof operator returns.

eerorika
  • 232,697
  • 12
  • 197
  • 326