LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   c++ pointer problems (https://www.linuxquestions.org/questions/programming-9/c-pointer-problems-531256/)

anon276 02-22-2007 03:08 AM

c++ pointer problems
 
I'm sure there's a few million threads on these.... and I'm sorry for bugging you folks again.

Here's the deal. I've got two arrays that are going to be interchanging. But it's specified I have to use pointers to swap them instead of doing it the easy way and using a temp variable to do the swap. Here's what I've got...

Code:

    int one[(arbitraty number];
    int two[(same arbitrary number)];
    int* addrhldr;
//For first element swap.
    addrhldr = &one[0];
    &one[0] = &two[0];
    &two[0] = addrhldr;

It's coming up with errors for the last two lines:
non-lvalue in assignment. I pulled it off somewhat like this once, but then I screwed with the code and now I want to bash my head into something because of this... Any help's appreciated.

wjevans_7d1@yahoo.co 02-22-2007 05:47 AM

Your compiler is trying to tell you that what you're doing doesn't make sense. It doesn't make sense to me either. (grin)

one is an array of integers. So is two. They're arrays of integers, not arrays of pointers. The only place you can store a pointer in this code, with the variables as they're declared now, is in addrhldr.

So how do you expect to swap pointers? You have only one pointer in the whole program.

If someone is specifying such a low-level detail that you have to swap pointers, then I'm assuming this is a class assignment. If that's the case, then fixing this problem (unless you deeply understand the fix) is not going to help you in the long run. You may wish to consult your instructor for some help on underlying concepts.

Hope this helps.

graemef 02-22-2007 06:15 AM

Sounds like a class assignment so...
How do you get the address of the first element of an array? (hint the answer is the same for any array)
Once you have answered that then you well earned hint is:

You need the address of the first element of both arrays, hence at least two pointers are required...

dmail 02-22-2007 08:09 AM

Have a look at std::iter_swap I think it is in the header algorithm, using this an graemef's hint is the key. You do not need to user the std function but you will be just reinventing the wheel if you don't.


All times are GMT -5. The time now is 12:54 PM.