#1
  1. Cast down
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    Sweden
    Posts
    321
    Rep Power
    11

    Passing char*, mallocing inside function


    Code:
    #include <stdlib.h> 
    #include <stdio.h> 
    #include <string.h> 
    
    void x(char *d); 
    
    int main(void) {
    	char *fff=NULL; 
    
    	x(fff); 
    	printf("%s\n", fff); 
    
    	free(fff); 
    	return 0; 
    }
    
    void x(char *d) {
    	d=(char*)calloc(500,1); 
    	strcpy(d, "t e x t---"); 
    	return; 
    }
    Can someone explain why this does not work?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2002
    Location
    NC, USA
    Posts
    364
    Rep Power
    12
    Getting any errors? What are you expecting and what is it really doing?
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,091
    Rep Power
    2222
    It's the old call-by-value trick.

    fff is a pointer to char which you initialize to NULL
    You pass the value of fff to the function x().
    x() stores the value of fff on the stack before it begins execution and calls it d.
    During execution, x() changes the parameter d on the stack; this does not in any way affect the variable fff.
    When x() returns, the parameter d goes away and no longer exists.
    fff never was touched by x() and so still contains its initial value of NULL.

    You need to pass to x() a pointer to the char pointer:
    Code:
    #include <stdlib.h> 
    #include <stdio.h> 
    #include <string.h> 
    
    void x(char **d); 
    
    int main(void) 
    {
    	char *fff=NULL; 
    
    	x(&fff); 
    	printf("%s\n", fff); 
    
    	free(fff); 
    	return 0; 
    }
    
    void x(char **d) 
    {
    	*d=(char*)calloc(500,1); 
    	strcpy(*d, "t e x t---"); 
    	return; 
    }
    Since x() now works with a pointer to fff, it can change the value of fff.

IMN logo majestic logo threadwatch logo seochat tools logo