Find the answer to your Linux question:
Results 1 to 5 of 5
Code: void change&#40;char *s&#41; &#123; s="change"; &#125; int main&#40;&#41; &#123; char *p="abc"; change&#40;p&#41;; cout<<p; return 0; &#125; according 2 me the ouput should be change but the outoput is abc ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Linux Newbie
    Join Date
    Mar 2005
    Location
    Bangalore, INDIA
    Posts
    122

    pointer magic


    Code:
    void change&#40;char *s&#41;
    &#123;
            s="change";
    &#125;
    
    int main&#40;&#41;
    &#123;
            char *p="abc";
            change&#40;p&#41;;
            cout<<p;
            return 0;
    &#125;
    according 2 me the ouput should be change but the outoput is abc
    any reasons why
    Portability is for people who cannot programme

  2. #2
    Linux Guru lakerdonald's Avatar
    Join Date
    Jun 2004
    Location
    St. Petersburg, FL
    Posts
    5,035
    try making it:
    Code:
    strcpy&#40;s, "change"&#41;;
    You'll have to include string.h

  3. #3
    Linux User
    Join Date
    Aug 2005
    Location
    Italy
    Posts
    401

    Argument by value

    All function arguments are passed by value: the value of the argument is copied.

    In the routine change, you don't modify the variable p declared in main, but its copy used as argument in the function chage... To modify variables you should use pointers, but because a" string" is just like a pointer, you must use a double pointer.

    A solution can be...

    [code]
    void change(char **s) /* double pointer! */
    {
    s="change";
    }

    int main()
    {
    char *p="abc";
    change(&p); /* we must pass a char** */
    cout<<p; /* Now prints "change" */
    return 0;
    }
    &#91;code&#93;&#91;/code&#93;
    When using Windows, have you ever told "Ehi... do your business?"
    Linux user #396597 (http://counter.li.org)

  4. #4
    Linux Guru lakerdonald's Avatar
    Join Date
    Jun 2004
    Location
    St. Petersburg, FL
    Posts
    5,035
    True. I would have just passed the function a pointer anyway.

  5. #5
    Super Moderator Roxoff's Avatar
    Join Date
    Aug 2005
    Location
    Nottingham, England
    Posts
    3,807
    And (seeing as how you're using C++) you can do this with a reference too!
    Linux user #126863 - see http://linuxcounter.net/

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •