What is the increment on a pointer for?

Asked

Viewed 175 times

1

Datum:

#include <stdio.h>

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

The exit is 2.

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

If this statement is correct, what change does the line refer to y= y + 1;? That is, what would be its use?

1 answer

1


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

In his example the expression y = y + 1 has no use, other than as described above, picking up junk from memory.

In another context where there could be a sequence of integers, probably initialized, it would be useful to pick up the next item of the sequence. Obviously this sequence would need to have a memory reserved somewhere, statically or dynamically, otherwise it would just pick up garbage, and worse, it could change something important to the application there.

I made a code to demonstrate how it works, but note that it’s practically a coincidence that works. Nothing in the language guarantees that what you see running 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

First I pick up the trash, then I start a new variable there and then I pick up the value at that address. This works because memory does not cease to be a sequence of data without an established criterion. In this specific case this sequence is a data stack.

In C you take care of the access to memory in hand. Do not take care and a lot can go wrong.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.