Search code examples
carrayspointersstrlengets

What happens when I use strlen() after incrementing a pointer?


I've done some research on strlen() and have a question.

Let's say I have an array of 50 elements and a pointer to the first element, meaning:

char A[50],*x;
gets(A);
x=&A[0];

From what I've understood, strlen(x) was supposed to give me the length of the string.

My question is, what exactly happens as I increment x?


Solution

  • First of all, and sorry for the digression, but please, never use the obsolete gets() function. Please use fgets instead.

    In answer to your question, if x is a pointer to a valid nonempty string, strlen(x+1) will always equal strlen(x) - 1.

    Suppose we have this string, with x pointing to it:

         +---+---+---+---+---+---+
      a: | H | e | l | l | o | \0|
         +---+---+---+---+---+---+
           ^
           |
       +---|---+
    x: |   *   |
       +-------+
    

    That is, x points to the first character of the string. Now, what strlen does is simply start at the pointed-to character and count characters until it finds the terminating '\0'.

    So if we increment x, now it points to the 'e' (that is, it points to the string "ello"), like this:

         +---+---+---+---+---+---+
      a: | H | e | l | l | o | \0|
         +---+---+---+---+---+---+
               ^
               |
              /
             /
            /
           |
       +---|---+
    x: |   *   |
       +-------+
    

    So strlen will get a length that's one less.


    Footnote: I'm reminded of an amusing bug I've come across more than once. When you use malloc to allocate space for a string, you always have to remember to include space for the terminating '\0'. Just don't do it this way:

    char *p = malloc(strlen(str + 1));
    

    My co-worker did this once (no, really, it was a co-worker, not me!), and it was stubborn to track down, because it was so easy to look at the buggy code and not see that it wasn't

    char *p = malloc(strlen(str) + 1);
    

    as it should have been.