简体   繁体   中英

How to swap between array and pointer c++

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.

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;
}

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM