swap two pointers to exchange arrays

和自甴很熟 提交于 2019-12-12 16:29:04

问题


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

回答1:


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



回答2:


You need to make the following change:

update_board2(&board, &new_board, rows, cols);

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

In this case pointers will be swapped correctly.




回答3:


your main needs to be fixed too

i.e.

char * new_board = (char *)malloc(sizeof(char) * rows * cols );
char * board = (char *)malloc(sizeof(char) * rows * cols );

malloc returns a pointer, not a character.



来源:https://stackoverflow.com/questions/13246615/swap-two-pointers-to-exchange-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!