Why does strlen() not represent the actual length of my string?

string length c++
sizeof(string c++)
size of string java
sizeof c
sizeof char array
length of char array c

basically I have a string composed of multiple words like this: "Hello world test". Either if I try to print it with a structure like this

printf("%s", string);

or like this

for (int i = 0; i < strlen(string); ++i) {
    printf("%c", string[i];

I always get this as an output: Hello world and I get a strlen of 11 instead of 16 too.

If I try to print out the same exact string with an int counter that previously counts the single chars in the string

for (int i = 0; i < counter; ++i) {
    printf("%c", string[i];

I actually get the correct output Hello world test, which leads be to believe that the elements are correctly assigned in the string but for some reason %s and strlen just ignores the ones after the last space.

Why would that happen? What is going on? How can I fix this?


Actual code as requested:

#include <stdio.h>
#include <string.h>
typedef int BOOL;
#define TRUE 1
#define FALSE 0

int main() {
    char sentence[64] = " ", reversal[64] = " ", reversal_copy[64] = " ";
    int index = 0, counter = 0;
    BOOL reset = TRUE, last_cycle = FALSE;

    printf("Enter a sentence: ");
    for (int i = 0; sentence[strlen(sentence) - 1] != '\n'; i++) {
        scanf("%c", &sentence[i]);

    /* Copies the input in a string reversing it */
    for (int h = strlen(sentence) - 2, k = 0; h >= 0; h--, k++) {
        reversal[k] = sentence[h];

    /* Detects the first character of a word and the last character of the same word before a space,
    switching the first char with the last, the second with the pre-last and so on*/
    for (int i = 0; i < strlen(reversal); i++) {
        if (reset == TRUE) {
            index = i;
            reset = FALSE;
        if (i == strlen(reversal) - 1) {
            last_cycle = TRUE;
        if (reversal[i] != ' ') {
            if (last_cycle == TRUE) {
                goto reversing;
        else {
            for (int h = index, z = counter; h < counter; h++, z--) {
                reversal_copy[h] = reversal[z - 1];
                reversal_copy[z - 1] = reversal[h];
            if (last_cycle == FALSE) {
                reversal_copy[i] = ' ';
            reset = TRUE;
    printf("%lu ", strlen(reversal_copy));
    for (int i = 0; i < counter; i++) {
        printf("%c", reversal_copy[i]);
    printf("%s\n\n", reversal_copy);

    return 0;

Try running your program with the input "A" as an example - see that even a single word exhibits the problem.

Something is going wrong when you reverse the last word. You are putting the trailing '\0' in front of it. It probably has to do with the special casing and the goto around the last_cycle logic, which is very hard to follow.

I think it's probably related to the fact that you have two counter++s in that code path.

Consider using some functions to make the code cleaner:

len = strlen(reversal);
for (start=0; start<len; start++) {
   end = find_space_or_null(reversal, start);
   if (end > start) {
    reverse_chars(reversal, start, end-1);
    start = end;

How does strlen() calculate the length of a string not defined in the , How does strlen likely compute the length of the string? Now, secondly, a C string does contain, explicitly, an indication of its length: all proper strings contain a null terminator, the special character '\0', which marks its end. How you determine a string's length is to read through it, counting characters, until you find the '\0'. That's exactly what strlen does. Finally, we come to your array d.

if strlen() returns 11 then you have a \0 char after the world "world".

strlen and printf both determine "what is a string" by using the 0 terminator, so no surprise that they behave the same.

is that char null terminator is including in the length count, Try running your program with the input "A" as an example - see that even a single word exhibits the problem. Something is going wrong when  The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (the unsigned integer type).. It is defined in the <string.h> header file.

While this is difficult to answer without a Minimal, Complete, and Verifiable example, I will explain the most likely reason for the behavior you're observing.

Both printf with the %s format specifier and strlen give you the length of the null-terminated string pointed to by the relevant argument. If they are printing/reporting a length of 11, but iterating through the entire char array with a hard-coded value of 16 gives you the output "hello world test", then the character after world is clearly the null character, '\0'.

C Program to Find the Length of a String, The main task of strlen() is to count the length of an array or string. strlen() is a predefined function in C; Data types supported: Sizeof gives actual size of any type of In context of C++: In C++, you do not need any of them as such. the number of elements present in the string before the NULL character, here which is 8. The main task of strlen() is to count the length of an array or string. sizeof vs strlen() Type: Sizeof operator is a unary operator whereas strlen() is a predefined function in C; Data types supported: Sizeof gives actual size of any type of data (allocated) in bytes (including the null values) whereas get the length of an array of chars/string.

the program takes a string inputted by the user like "the sky is blue" and prints out "blue is sky the"

That's a perfect job for strtok():

#include <stddef.h>
#include <stdio.h>
#include <string.h>

enum { MAX_LINE = 120 };

int main()
    char buffer[MAX_LINE];
    fgets(buffer, MAX_LINE, stdin);

    size_t length = strlen(buffer);
    if (length && buffer[length - 1] == '\n')  // get rid of the newline
        buffer[--length] = '\0';

    char *tokens[MAX_LINE] = { 0 };  // there can't be more than 60 tokens, but hey
    if ((tokens[0] = strtok(buffer, " ")) == NULL)  // no tokens? nothing to do.
        return 0;

    size_t i = 1;
    for (; tokens[i - 1] && i < sizeof(tokens); ++i)
        tokens[i] = strtok(NULL, " ");  // tokenize the buffer

    --i;  // the very last was NULL anyway.
    while (--i)  // print it reverse
        printf("%s ", tokens[i]);
Sample Output:
The quick brown fox jumps over the lazy dog
dog lazy the over jumps fox brown quick The

Why does strlen() not represent the actual length of my string , The “string library” was nothing more than a collection of rather primitive In the C language, strings are represented as an array of characters. The strlen() function returns the length of the string, not the amount of memory needed to hold it. for a string is to add 1 to the amount of space needed for the actual characters. To me, this sounds more like a problem with the PHP function not doing what the name is suggests it does. There is no mention on the documentation for either strlen() or mb_strlen that this is the case… it’s just shoddy work on behalf of the PHP development team

Difference between strlen() and sizeof() for string in C, P-string: • The string is represented using one more element than the content sug​- gests; The actual string content cannot contain a NUL character, otherwise we There is no real restriction on the string length, but we do not have direct access to that length. 4.2 String Algorithms 4.2.1 strlen: Finding the Length of a String. The strlen() function calculates the length of a given string.The strlen() function is defined in string.h header file. It doesn’t count null character ‘\0’. It doesn’t count null character ‘\0’.

Professional C++, This does not include the null “character” which indicates string termination. Thus the actual storage necessary to store a string in C is one more than its osten Pradip Gangoda, Lecturer in Department of Computer (2013-present). The strlen() Function. Syntax: size_t strlen (const char* str); Note: For this chapter ignore the keyword const. It will be discussed later. The strlen() accepts an argument of type pointer to char or (char*), so you can either pass a string literal or an array of characters.

What Is Computer Science?: An Information Security Perspective, 5.3 String Length. You can get the length of a string using the strlen function. But beware, this will not work unless string is the array itself, not a pointer to it. @Guy.D the code you posted is using char arrays, not String objects. Majenko's answer is what you need, not String.length(). Note that you need to be careful not to overflow your char array. That will cause undefined behavior (read "bugs.") – Duncan C Jan 18 at 22:00

  • How does the value "Hello world test" get into string? minimal reproducible example?
  • typedef int BOOL; ~> #include <stdbool.h> for gods sake. What is that program supposed to do (I am too lazy to try to figure it out from the code)? The correct format specifier for size_t the result of strlen() is "%zu" btw.
  • for (int i = 0; sentence[strlen(sentence) - 1] != '\n'; i++) { is very odd. you should test sentence[i] inside the loop, after assigning it.
  • if you dont believe it then change your test printf(%c) loop to a printf(%x) loop. You will see a 0 in there (rather than a 20 )
  • Side note: strlen has non-zero execution cost, so try to avoid it in a for loop condition clause. Better: int revlen = strlen(reverse); for (int i = 0; i < revlen; i++) { and likewise replacing it within that loop. Otherwise, if your length was N, you'll do N*N scans of the chars in the string.