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

void print_reverse(char *s)
{
    size_t len = strlen(s);
    char *t = s + len - 1;
    while (t >= s)
    {
        printf("%c", *t);
        t = t - 1;
    }
    puts("");
}

Above is a function that will display a string backward on the screen. But I don't understand the 7th line (char *t = s+ len-1;). Could anybody explain this is spoken English please?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

2 Answers2

7

For starters this function

void print_reverse(char *s)
{
    size_t len = strlen(s);
    char *t = s + len - 1;
    while (t >= s)
    {
        printf("%c", *t);
        t = t - 1;
    }
    puts("");
}

is wrong and has undefined behavior.:)

There are two problems.

The first one is that the passed string as the argument can have a zero-length. In this case this declaration

char *t = s + len - 1;

will look like

char *t = s - 1;

and the pointer t can be wrong.

The second problem is that this expression statement

t = t - 1;

has undefined behavior in case when the pointer t is equal to s.

From the C Standard (6.5.6 Additive operators)

  1. ...If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

A correct function implementation can look the following way

void print_reverse( const char *s)
                    ^^^^^
{
    size_t len = strlen(s);
    const char *t = s + len;
                    ^^^^^^^
    while (t != s)
           ^^^^^^
    {
        printf("%c", *--t);
                     ^^^^
    }
    puts("");
}

As for your question then in this declaration

char *t = s + len - 1;

the pointer t is tried to be initialized by the address of the last character of the string before the terminating zero.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

Main logic behind this functions is that this code:

char *t = s+ len-1;

return a pointer to the address of the last char in the char pointer you are passing to the function. The loop prints it by decrementing it:

t = t - 1;

So in simple words it prints the char pointer from backwards.

du4ko
  • 101
  • 6