Decrement, increment and sum of pointers in C

0

When I try to add the last pointer over 15, it repeats the third-to-last pointer and does not add the pointer *ptr_xi to it with a further 15?

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);
}
    
asked by anonymous 14.07.2018 / 04:52

1 answer

1

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

In the latter is the only one that is adding pointer. Manipulate the pointer itself. It is going 15 memory locations ahead of the original position where was the value you want to manipulate. As it 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 junk, something that you have no control, then will access an area with information that we can say almost random, or where it can not.

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 you have a pointer you have two information the pointer address and the value that is pointed to. When you manipulate the pointer variable you are manipulating the memory address. When you want to manipulate the value, you have to get the address, make the indirection to the location indicated and there is the value manipulated, so you used parentheses to get the location first and then do the operation. In the latter he manipulated the place and then took the value in that new place.

    
14.07.2018 / 07:18