Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why pointer is still NULL after function calling? 2

Status
Not open for further replies.

abcd12344445555

Programmer
May 10, 2009
24
0
0
BR
In the following code why does the pointer [highlight]head[/highlight] is still null after function calling? Thanks.

Code:
#include <stdio.h>
#include <stdlib.h>

struct list_element{
   int info;
   struct list_element * next;       
};

typedef struct list_element item;

void alloc(item *head){
     
     printf("%p\n", head);
     
     head = (item * ) (malloc(sizeof(item)));

     if(head){
         printf("malloc ok! : %p\n",head);
     }
}
     

int main(int argc, char *argv[])
{
   item [highlight]*head[/highlight];
   [highlight]head[/highlight] = NULL; 
   
   alloc([highlight]head[/highlight]);
   
   //Why after this point head is still NULL?

   if([highlight]head[/highlight] == NULL){
   printf("null\n");        
   }
   else{
       printf("Not null!\n");
   }
   
   printf("ptr main : %p\n", [highlight]head[/highlight]);
   system("PAUSE");	
   return 0;
}
 
Try this...

Code:
#include <stdio.h>
#include <stdlib.h>

struct list_element{
   int info;
   struct list_element * next;       
};

typedef struct list_element item;

void alloc(item [highlight]**head[/highlight]){
     
     printf("%p\n", [highlight]*head[/highlight]);
     
     [highlight]*head[/highlight] = (item * ) (malloc(sizeof(item)));

     if([highlight]*head[/highlight]){
         printf("malloc ok! : %p\n",[highlight]*head[/highlight]);
     }
}
     

int main(int argc, char *argv[])
{
   item *head;
   head = NULL;
   
   [highlight]alloc(&head);[/highlight]
   
   //Why after this point head is still NULL?

   if(head == NULL){
   printf("null\n");        
   }
   else{
       printf("Not null!\n");
   }
   
   printf("ptr main : %p\n", head);
   system("PAUSE");    
   return 0;
}
You're putting your pointer on the stack and that's the one that's being updated from the malloc(). So that gets lost on function return.

You need to pass a pointer to your pointer. Give the function alloc() the address of your pointer and it should be ok.

 
Everything is passed by value, including pointers. When you pass a pointer, a copy of the address is made in the function. It's the same as if you were doing this:
Code:
char* str1 = NULL;
char* str2 = str1;
str2 = malloc(20);  // This doesn't change str1.

If you want to update the value of your pointer (i.e. the address) then you need to pass it by reference by adding another pointer as SamBones illustrated.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top