如何链接这两个功能

时间:2018-11-22 15:49:43

标签: c function pointers

我需要做什么更改change_sequence_2()才能从tausche_2()获取信息?

void tausche_2 (char *c1, char *c2)
{
    char temp;
    temp = *c1;
    *c1 = *c2;
    *c2 = temp;
}

void change_sequence_2(char *F)
{
    int i, j;
    i = 0;
    j = strlen(F) - 1;
    while (i < j) {
        tausche_2 (F, i, j);
        i = i + 1;
        j = j - 1;
    }
}

1 个答案:

答案 0 :(得分:0)

由于您的tausche_2()将其两个参数用作指针并取消引用它们,因此它将对您传递给它的地址的值进行操作。当前,您尝试传递3个参数,其中只有一个是指针。从change_sequence_2()调用它的正确方法是:

tausche_2(&F[i], &F[j]);  // I use the address-of operator to make clear for you,
                          // that this will pass the adresses of the elements at
                          // position `i` and `j`.

或者,您可以将偏移量ij添加到F

tausche_2(F + i, F + j);  // to get the same addresses.

tausche_2()中,传递的指针被*取消引用:

temp = *c1;  // assigns temp the value pointed to by c1
*c1 = *c2;   // assigns the value pointed to by c1 the value pointed to by c2
*c2 = temp;  // assigns the value pointed to by c2 the value of temp

因此tausche_2()像上面那样被有效地操作在char *F的参数change_sequence_2()所指向的存储器上。