Search code examples
cmemorypointerstemp

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?


Solution

  •     int* p_numbers = ((int*) malloc (5*sizeof(int)));  
    
                  +---+---+---+---+---+ 
    p_numbers --> | x | x | x | x | x |
                  +---+---+---+---+---+ 
    
    
        int* temp;  
        temp = p_numbers;  
    
    p_numbers --+    +---+---+---+---+---+ 
                +--> | x | x | x | x | x |
    temp--------+    +---+---+---+---+---+ 
    

    you need also to free p_numbers since otherwise you get a memory leak.

    also please make a habit of not casting the return value from malloc because in some cases this can cause hard to find errors

    explanation:

    the malloc is defined stdlib.h, if you forget to include that header, the malloc function will by default assumed to return int as that is the way in C for functions that have no prototype. Now if you have something like char*p = (char*)malloc(12); this may cause issues because you effectively casting the returned integer to a char*. By explicitly casting you silence the warnings from the compiler and if you have hardware/OS where sizeof(char*) != sizeof(int) you may get a hard to find error so just write

    p_numbers = malloc(5*sizeof(int))

    if you are using a C++ compiler, use new/delete instead.