【问题标题】:How to link the 2 functions如何链接这两个功能
【发布时间】:2018-11-22 15:49:43
【问题描述】:

我需要做什么来改变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;
    }
}

【问题讨论】:

标签: c function pointers


【解决方案1】:

由于您的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() 当像上面那样调用时,会有效地对change_sequence_2() 的参数char *F 指向的内存进行操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多