I'm relatively new to C and I was pretty sure I had a decent understanding of pointers and how they are used. However, I was just playing around with the concept of Pass by Reference and came across a bit of a delima. Hopefully someone can help explain this to me....
I have 2 small programs to test my knowledge of pass by reference and I wanted them both to have the same results however they do not:
Program 1
Program 2Code:#include <stdlib.h> #include <stdio.h> int main(){ char* hostname= (char*)calloc(10, sizeof(hostname)); hostname = "unchanged"; printf("Address of hostname = %d\n", &hostname); someFunction(&hostname); printf("Hostname: %s\n", hostname); return 0; } someFunction(char** s){ printf("s = %d\n", s); printf("Address of s = %d\n", &s); printf("*(&s) = %d\n", *(&s)); *s = "changed"; }
The results of Program 1 gives me what I expected which was hostname being changed to "change":Code:#include <stdlib.h> #include <stdio.h> int main(){ char* hostname = (char*)calloc(10, sizeof(hostname)); hostname = "unchanged"; printf("Address of hostname = %d\n", &hostname); someFunction(&hostname); printf("Hostname: %s\n", hostname); return 0; } someFunction(char* s){ printf("s = %d\n", s); printf("Address of s = %d\n", &s); printf("*(&s) = %d\n", *(&s)); *(&s) = "changed"; }
Address of hostname = -1073845548
s = -1073845548
Address of s = -1073845584
*(&s) = -1073845548
Hostname: changed
The results of Program 2 do not give me what I expected. Can someone please tell my why hostname does not get "changed" in this example?
Address of hostname = -1074574892
s = -1074574892
Address of s = -1074574928
*(&s) = -1074574892
Hostname: unchanged



LinkBack URL
About LinkBacks



