交换两个指针数组交换

交换两个指针数组交换

本文介绍了交换两个指针数组交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code,我希望让这个委员会现在有new_board的价值,反之亦然。由于他们都是指针我想我可能只是交换它们指向的地址。当我print2打印()地址适当交换。然而,当我在PRINT1打印()地址莫名其妙地交换回,它没有任何意义,我。另外,如果我在局print2打印出来的值()他们也是正确的。

 的main(){
  字符* new_board =(字符*)malloc的(的sizeof(char)的*行* COLS);
  字符*板=(字符*)malloc的(的sizeof(char)的*行* COLS);
  update_board2(板,new_board,行COLS);
  PRINT1();
}无效update_board2(字符*板,字符* new_board,诠释行,诠释COLS){
  //做一堆东西
  字符* TEMP =板;
  板= new_board;
  new_board =温度;
  print2();
}


解决方案

如果你想改变指针本身,那么函数 update_board2 的值必须接受双重指针。否则,得到的指针函数内复制和你交换只有这些临时副本而不是真正的指针调用者已通过:

 无效update_board2(字符**板,焦炭** new_board){
  字符* TEMP = *板;
  *板= * new_board;
  * new_board =温度;
  print2();
}

I have the following code which I want to make it so that board now has the value of new_board and vice versa. Since they are both pointers I thought I could just swap the addresses they point to. When I print in print2() the addresses are appropriately swapped. However, when I print in print1() the addresses have somehow swapped back, which doesn't make any sense to me. Further if I print out the values in the board at print2() they are also correct.

main(){
  char *new_board = (char *)malloc(sizeof(char) * rows * cols );
  char *board = (char *)malloc(sizeof(char) * rows * cols );
  update_board2(board, new_board, rows, cols);
  print1();
}

void update_board2(char *board, char *new_board, int rows, int cols){
  //do a bunch of stuff
  char *temp = board;
  board = new_board;
  new_board = temp;
  print2();
}
解决方案

If you want to change the values of the pointers themselves, then the function update_board2 has to accept double pointers. Otherwise the pointers get copied within the function and you are swapping only these temporary copies rather than the real pointers the caller has passed:

void update_board2(char **board, char **new_board){
  char *temp = *board;
  *board = *new_board;
  *new_board = temp;
  print2();
}

这篇关于交换两个指针数组交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:51