Difference between ptr++ and ptr + 1

I wrote a code to reverse a string using recursion. When I run it, I get a segmentation error.

#include <stdio.h>

void _print_rev_recursion(char *s);

int main() {

    _print_rev_recursion("string reversal");

    return (0);

}

void _print_rev_recursion(char *s)

{

    if (!*s)

        return; 

    _print_rev_recursion(s++);

    putchar(*s);

}

When I changed s++ to s + 1, the code works.
I thought both s++ and s+1 mean the same thing. I need clarification please.

This is the code that works:


#include <stdio.h>

void _print_rev_recursion(char *s);

int main() {

    _print_rev_recursion("string reversal");

    return (0);

}

void _print_rev_recursion(char *s)

{

    if (!*s)

        return; 

    _print_rev_recursion(s + 1);

    putchar(*s);

}

>Solution :

ptr++ is a postfix increment operator, while ptr + 1 is an arithmetic expression that adds 1 to the value of ptr.

The main difference between the two is that ptr++ increments the value of ptr by 1 after the current statement has been executed, while ptr + 1 adds 1 to the current value of ptr but does not change the value of ptr itself.

For example, consider the following code:

int i = 1;
int j = i++;

After this code has been executed, the value of i will be 2, but the value of j will be 1, because the postfix increment operator increments the value of i after it has been assigned to j.

On the other hand, consider the following code:

int i = 1;
int j = i + 1;

After this code has been executed, the value of i will still be 1, but the value of j will be 2, because the arithmetic expression i + 1 adds 1 to the current value of i but does not change the value of i itself.

Leave a Reply