-1

I thought quite a lot about the character string length in c, character string terminates with null character which is '\0', it is not visible in text, as we can see from the c code:

#include <stdio.h>
#include <string.h>
int main(){
    char s1[] = "ould";
    printf("ould string length is %ld\n", strlen(s1));
    char s2[] = {'o','u','l','d','\0'};
    printf("ould string length is %ld\n", strlen(s2));
    return 0;
}

the book said at the end of section 3.9, s2 is equivalent, but the array size is 5, from the running result, it is 4,from my understanding and search, string ends with '\0', but '\0' will not be included as the string length, but why the author said it is 5? could anyone share ideas or clarity on this??

Thomas
  • 107
  • 1
  • 10
  • 3
    `strlen` is not an array size. It is size of the string up to (and not including) `'\0'`. The array including it might be much larger. – Eugene Sh. Mar 22 '21 at 13:43
  • 1
    Please post code, errors, sample data or textual output here as plain-text, not as images that can be hard to read, can’t be copy-pasted to help test code or use in answers, and are barrier to those who depend on screen readers or translation tools. You can edit your question to add the code in the body of your question. For easy formatting use the `{}` button to mark blocks of code, or indent with four spaces for the same effect. The contents of a **screenshot can’t be searched, run as code, or copied and edited to create a solution.** – tadman Mar 22 '21 at 13:43
  • An array of characters holding a string must be at least 1 character larger than the string it is holding to have room for the terminating null character. The string _length_ excludes this terminating null character. So the array has size 5, the string has length 4. – Paul Ogilvie Mar 22 '21 at 13:47
  • The string length is 4, the character array size is 5. A character array can be used to represent a string if there's room for a null terminator. And that's about it. See the linked duplicate. – Lundin Mar 22 '21 at 13:47

2 Answers2

2

Don't confuse sizeof(x) with strlen(x). The sizeof operator returns the in-memory footprint of something:

char buffer[1024] = "Test";

Here sizeof(buffer) is 1024 while strlen(buffer) is 4, yet in another case:

char* buffer = "Testing string";

Here sizeof(buffer) is 8 (64-bit) while strlen(buffer) is 14.

tadman
  • 208,517
  • 23
  • 234
  • 262
1

The length of a string is the number of characters in it before the first null character. The length of the string containing the characters o, u, l, d, and a null character is four.

The size of an array is the number of bytes in the array (or, in some contexts, the number of elements in the array). The size of an array containing the characters o, u, l, d, and a null character is five.

strlen(s2) returns the length of the string in s2.

sizeof s2 evaluates to the size of the array s2.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312