Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


#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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading