Decrease, increment and sum of pointers in C

Asked

Viewed 572 times

0

Why when I try to add the last pointer to another 15 it repeats the second to last pointer and does not add the pointer *ptr_xi with 15 others?

int xi;

int *ptr_xi;

void imprimir() 

    printf("valor de xi = %d \n", xi);
    printf("valor de &xi = %p \n", &xi);
    printf("valor de ptr_xi = %p \n", ptr_xi);
    printf("valor de *ptr_xi = %d \n\n", *ptr_xi);
}

main() 
{

    xi = 10;
    ptr_xi = ξ
    imprimir();

    xi = 20;
    imprimir();

    *ptr_xi = 30;
    imprimir();

    (*ptr_xi)--;
    imprimir();

    (*ptr_xi)++;
    imprimir();

    (*ptr_xi)++;
    imprimir();

    *(ptr_xi+15);
    imprimir();

    system ("Pause");
    return(0);
}
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

In all of the above you are not adding pointers, you are adding up values pointed by pointer variables. This is very different, doing what you probably wanted, changing the associated values. None of this is necessary pointer, can serve to visualize what happens, but be careful not to find that this is how you use pointer.

In the latter is the only one that is adding pointer. Manipulates the pointer itself. It is going 15 memory positions ahead of the original position where was the value it wants to manipulate. As is a int probably (not sure, it depends on the platform) it has 4 bytes, so 15 positions are 60 bytes ahead. What has 60 positions ahead? In this case it’s garbage, something you have no control over, so you’re going to access an area with information that we can say is almost random, or up to where you can’t.

Whenever you have a pointer the value of the variable is a memory address, note that you used a operator & to get the memory address where it had a value. When a pointer has two information the pointing address and the value that is pointed. When you manipulate the pointer variable you are manipulating the memory address. When you want to manipulate the value, you have to take the address, do the indirect to the point and there manipulates the value, so you used parentheses, to first pick up the location and then do the operation. The last one manipulated the place and then took the value in this new place.

Browser other questions tagged

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