Redraw the pointer?

Can someone help me understand the following. I am reassigning the pointer and using a temporary value to get the content it points to. I see no reason why case 1 should work and case 2 shouldn't.

// Case 1: This works:

void main (void){

    unsigned int  nr1;
    unsigned int  nr2;
    unsigned int  * ptr_int;
    unsigned int temp1_value;
    unsigned int temp2_value;

    while(1){

        nr1 = 0x1234;
        ptr_int= &nr1;
        temp1_value  = *(ptr_int); // Copy nr1 to temp1_value

        nr2 = 0x5678;
        ptr_int= &nr2;
        temp2_value  = *(ptr_int); // Copy nr2 to temp2_value

    }
}

      

// Case 2: This doesn't work (if I go step by step temp1_value doesn't change)

void main (void){

    unsigned int  nr1;
    unsigned int  nr2;
    unsigned int  * ptr_int;
    unsigned int temp1_value;
    unsigned int temp2_value;

    while(1){

        nr1 = 0x1234;
        ptr_int= &nr1;
        temp1_value  = *(ptr_int); //Copy nr1 to temp1_value

        nr2 = 0x5678;
        ptr_int= &nr2;
        temp1_value  = *(ptr_int); //Copy nr2 to temp1_value

    }
}

      

I'm sure this is something basic, but I can't point to it.

Am I not allowed to reassign a pointer?

Thank.

Edit: It's built in C. Target is 8051 microcontroller.

+3


source to share


1 answer


Thanks Jeremy and Lundin.

If someone else stumbles upon something like this, changing

unsigned int temp1_value;

      



to

volatile unsigned int temp1_value;

      

gives the expected behavior.

+2


source







All Articles