Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Pointer and temp variable

int main()  
{  
    int i=0;  
    int* p_numbers = ((int*) malloc (5*sizeof(int)));  
    int* temp;  
    temp = p_numbers;  
    for(i=0;i<5;i++)  
    {  
        *temp=i;   
        printf("temp %d p_numbers %d",*temp,*p_numbers);  
        temp++;           
    }
}

Please tell that the pointer assigned to temp i.e temp=p_numbers.

DOES temp not point to the same memory position where the p_numbers is pointing to?

like image 662
anshulkatta Avatar asked Aug 25 '26 06:08

anshulkatta


1 Answers

The variables temp and p_numbers will point to the same memory location on the first iteration of the loop. Afterwards, temp is incrementing by an integer, but p_numbers won't.

Because of the assignments, p_numbers = [0,1,2,3,4], so you will print out:

temp 0 p_numbers 0
temp 1 p_numbers 0
temp 2 p_numbers 0
temp 3 p_numbers 0
temp 4 p_numbers 0

Think of pointers as pointing to a memory address and not more like the Java reference syntax.

like image 125
nmjohn Avatar answered Aug 27 '26 20:08

nmjohn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!