`

c - pointer is also pass by value

 
阅读更多

 

c - pointer is also pass by value

 

when pointer as param of function, it is also pass by value:

* you can change the value that the pointer point to by the address(the value of pointer),

* but you can't change the original value of pointer in the function,

* if you want to change the pointer, you need to return the new address from function, and assign it to the pointer outside the function,


e.g.
    pass_by_value.c:
#include <stdio.h>
#include <string.h>

char *test(char *s) {
	s = strdup("s2");
	return s;
}

main() {
	char *s1;
	s1 = "s1";
	printf("%s\n", s1);	// s1
	
	test(s1);
	printf("%s\n", s1);	// s1, because pointer param of function is also pass by value, you can't change the original value of pointer in the function, even though you can change the value it point to by the address(the value of pointer).
	
	s1 = test(s1);
	printf("%s\n", s1);	// s2, because new address is returned from function, and assign to pointer outside the function.
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics