Connecting Tech Pros Worldwide Forums | Help | Site Map

Simple pass-by-reference question

Member
 
Join Date: Aug 2007
Posts: 42
#1: Jul 3 '08
How do I get the pass by reference-thing to work in this example?
Since I'm still new to C I sometimes get confused in this matter, and this is one of those occasions.

I'm obviously doing something wrong.
Expand|Select|Wrap|Line Numbers
  1. int main(void)
  2. {
  3. char *params =  mem_alloc(sizeof(char)*64);
  4. getParams(params);
  5. printf("Parameters: %s",params);
  6. mem_free(params);
  7. }
  8.  
  9. int getParams(char *p)
  10. {
  11.   p = "something, something";
  12.   return 0;
  13. }
what I want is of course the result to be "Parameters: something, something".
Thanks!

JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#2: Jul 3 '08

re: Simple pass-by-reference question


There doesn't exist a call by reference parameter passing mechanism in C; it only
uses call by value for passing parameters around. You can still copy your string
to that chunk of memory. Change your line 11 as follows:

Expand|Select|Wrap|Line Numbers
  1. strcpy(p, "something, something");
  2.  
kind regards,

Jos
Member
 
Join Date: Aug 2007
Posts: 42
#3: Jul 3 '08

re: Simple pass-by-reference question


Ok, thank you very much, my problem is solved!
However, I'm trying to really understand why just writing
Expand|Select|Wrap|Line Numbers
  1. p="something,something";
  2.  
doesn't work. While debugging, I see that the params-pointer and the p-pointer both point to the same address. That's why I'm confused.
But is it because the pointer p only gets assigned to point to the string 'locally', so once we're outside the scope of the getParam - method, this assignment is all forgotten about? If that's the case, I think I understand. Anyhow, again thank you so very much!
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#4: Jul 3 '08

re: Simple pass-by-reference question


Quote:

Originally Posted by MimiMi

But is it because the pointer p only gets assigned to point to the string 'locally', so once we're outside the scope of the getParam - method, this assignment is all forgotten about? If that's the case, I think I understand. Anyhow, again thank you so very much!

Yep, that's how call by value works: just values are passed to a function and
assigned to the parameters as if they were local variables. If you change them
you don't change anything outside that function. If such a value happens to be
an address and you change some memory content at that address, the changes
will be permanent then, i.e. not local to that function.

kind regards,

Jos
Reply