Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2007
    Location
    Vilnius/Lithuania
    Posts
    254

    pointer issue (simple one)

    Hey. I recently was creating my class and needed to have a pointer pointing to a function result, though I could not declare that due to errors that kept popping up
    Could some check that and maybe tell me, where I am wrong?

    int *linker;
    linker = &sum();

    I get the error: "non-lvalue in unary '&' "
    Any ideas, what is wrong?

    Thanks in advance!
    "I do not know with what weapons World War 3 will be fought, but World War 4 will be fought with sticks and stones." - A. Einstein

  2. #2
    Join Date
    Apr 2003
    Location
    CT
    Posts
    370
    I believe you need a void pointer.
    void *linker;

  3. #3
    Join Date
    Jun 2003
    Location
    Trier, Germany
    Posts
    1,350
    you can't take a (non-const) reference of an rvalue. that's how rvalues are defined.

    i'm assuming your function's signature looks somewhat like this:
    Code:
    int sum() {
        ...
    when this function returns, the (unnamed) return value is pushed to the stack, but it will be immediately removed (popped from the stack) once the function return completes. i.e. if you were allowed to take a pointer to this unnamed value, that pointer would become invalid on the very next line.
    hope this makes sense. if not, please ask, as this is quite an important issue.

    resolving this is simple: copy the value to a regular (named) storage specifier, i.e. a variable of type int. you can then take a pointer to that variable.

    and don't you ever succumb to the incredibly stupid idea of returning a pointer to a variable local to sum(). you should be able to figure out why
    Last edited by ComicSansMS; 10-29-2009 at 11:01 AM.

  4. #4
    Join Date
    Jul 2007
    Location
    Vilnius/Lithuania
    Posts
    254
    Thank you both - that worker :] I mean I just created new variable that holds the value of function returned value, then I used pointer to address that storage with the value.

    P.S.: you know... before this site, I have tried many others and found out one thing - there you get answer the same day you post the question and it helps 100% (at least for me)
    Excelet site and support!
    "I do not know with what weapons World War 3 will be fought, but World War 4 will be fought with sticks and stones." - A. Einstein

Posting Permissions

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