1

I am trying to swap between array and pointer in c++

My code is as the following :

void foo(int* a, int* b);
void main()
{
  int *a = NULL;
  int b[6]={2,3,5,6};
  foo(a,b);
}

void foo(int* a, int b[])
{
  int * c;
  c=a;
  a=b;
  b=c;
}

While I return out from the Method nothing changed ,

within the method everything work fin but when the method return nothing change.

my question is:

A) what is my mistake.? B) How should I fix it.

1
  • 6
    If your book or professor taught you void main(), it's time to swap that one. Commented Apr 1, 2012 at 8:25

2 Answers 2

7

Your mistake is that you assume arrays are pointers. They are not. They can decay to pointers.

You can't change b, but you can change a, by passing it by reference:

void foo(int*& a, int b[])
{
  int * c;
  c=a;
  a=b;
}
Sign up to request clarification or add additional context in comments.

Comments

0

In your example, b is allocated. But you can't transfer this "being allocated" property of an array to a pointer. You can allocate a pointer (by using malloc or new) but you can't de-allocate an array. So I'm afraid what you want to do isn't possible.

If all you want to do is exchange the contents of a and b, you'll have to do that the hard way (physically copy each value, or memcpy for the whole array at once), but you can't simply change the array in such a way that its address changes to that of a.

(Obligatory remark: since you tagged your question c++, you should use vectors.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.