What is the purpose of incrementing a pointer?

0

Given:

#include <stdio.h>

int main ()
{
    int x = 1;
    x++;
    int *y = &x;
    y = y + 1;
    printf("%d\n",x );
}

The output is 2.

In this case, I would like to know if the following interpretation is correct: y = y + 1; only modifies the address, that is, it adds 1 that means 4 positions with respect to x, but the value of x does not change, the x++; line.

If this statement is correct, what change refers to the y= y + 1; line? That is, what would be your service?

    
asked by anonymous 25.10.2016 / 00:36

1 answer

1

Your understanding is correct, what is being done with y is to change the location that it points, it will point to the next memory address, which will have garbage left in memory.

In this example, the expression y = y + 1 is of no use, except as described above, get garbage from memory.

In another context where you could have a sequence of integers, probably initialized, it would be useful to get the next item in the sequence. Obviously this sequence would need to have a reserved memory somewhere, either static or dynamically, otherwise it would only take garbage, and worse, it could change something important for the application there.

I've made a code to demonstrate how it works, but note that it's almost a coincidence that it works. Nothing in the language guarantees that what will happen in this example will happen.

#include <stdio.h>

int main() {
    int x = 1;
    x++;
    int *y = &x;
    y++;
    printf("%d, %d\n", x, *y);
    int z = 5;
    printf("%d, %d\n", z, *y);
}

See working on ideone and on CodingGround .

First I get the garbage, then I initialize a new variable there and then I get the value at that address. This works because memory is no longer a data stream without a set criteria. In this particular case this string is a data stack .

In C you take care of memory access at hand. Do not be careful and a lot can go wrong.

    
25.10.2016 / 01:24