0

我正在尝试用两个表指针交换两个字符。有人可以向我解释我的代码有什么问题吗?终端说char** is expected但我不知道该怎么做,所以我想我并不真正了解指针如何为表工作。

void echangeM2(char **ptab1, char **ptab2){

  char *tmp = *ptab1;
  *ptab1 = *ptab2;
  *ptab2 = *tmp;
  printf("%s\t %s",*ptab1,*ptab2);

  return;
}

int main(void) {
  char tab1[25];
  char tab2[25];
  char *adtab1;
  char *adtab2;
  *adtab1 = &tab1;
  *adtab2=&tab2;
  printf("type two words");
  scanf("%s %s",tab1,tab2);
  echangeM2(adtab1,adtab2);
  return 0;
}
4

2 回答 2

1

以下代码应该适合您:

#include <stdio.h>

void exchangeM2(char* *ptab1, char* *ptab2) { // accepts pointer to char*
  char* tmp = *ptab1;  // ptab1's "pointed to" is assigned to tmp
  *ptab1 = *ptab2;     // move ptab2's "pointed to" to ptab1
  *ptab2 = tmp;        // now move tmp to ptab2
  printf("%s\t %s",*ptab1,*ptab2);
}

int main(void) {
  char tab1[25];
  char tab2[25];
  char* adtab1;
  char* adtab2;
  adtab1 = tab1;  // array name itself can be used as pointer
  adtab2 = tab2;
  printf("type two words");
  scanf("%s %s",tab1,tab2);
  exchangeM2(&adtab1, &adtab2);  // pass the address of the pointers to the function
}
于 2012-12-16T15:51:08.503 回答
0
echangeM2(&adtab1,&adtab2); 

这应该可以修复编译错误。您正在将指针传递给需要指针char*的函数char **

编辑:实际上看起来你想要类似的东西

char **adtab1;
char **adtab2;
adtab1 = &tab1;
adtab2=&tab2;
...
echangeM2(adtab1,adtab2);
于 2012-12-16T15:50:50.763 回答