Simple pass-by-reference question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MimiMi
    New Member
    • Aug 2007
    • 42

    Simple pass-by-reference question

    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.
    Code:
    int main(void)
    {
    char *params =  mem_alloc(sizeof(char)*64);
    getParams(params);
    printf("Parameters: %s",params);
    mem_free(params);
    }
    
    int getParams(char *p)
    {
      p = "something, something";
      return 0;
    }
    what I want is of course the result to be "Parameters : something, something".
    Thanks!
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    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:

    [code=c]
    strcpy(p, "something, something");
    [/code]

    kind regards,

    Jos

    Comment

    • MimiMi
      New Member
      • Aug 2007
      • 42

      #3
      Ok, thank you very much, my problem is solved!
      However, I'm trying to really understand why just writing
      [code=c]
      p="something,so mething";
      [/code]
      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!

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        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

        Comment

        Working...