C指针的设置不等于另一个


    void s(int* a, int* b) {
        a=b;
    }
    int main(int argc, char* argv[]) {
        int* a = malloc(sizeof(int));
        int* b = malloc(sizeof(int));
        int c = 10;
        int d = 5
        a = &c;
        b = &d;
        printf("%d %dn",*a,*b);
        s(a,b);
        printf("%d %dn",*a,*b);
    }

我非常困惑。这是非常简单的代码。我认为这将导致A和B指向相同的值。当我在主函数内部进行A = B时,一切都按预期工作。当我使用GDB时,它甚至表明它们指向内存中的同一位置,并且该功能不会被优化!!!那怎么了?功能是创建自己的本地副本吗?为什么不指出相同的变量,请提供帮助。

您想更改指针值。指针按价值传递,因此您需要指向指针更改其值的指针:

#include <stdio.h>
void s(int** foo, int** bar)
{
    *foo = *bar;
}
int main(void)
{
    int c = 10;
    int d = 5;
    int *a = &c;
    int *b = &d;
    printf("%d %dn", *a, *b);  // 10 5
    s(&a, &b);
    printf("%d %dn", *a, *b);  // 5 5     a points at d as well
}

使用您的版本,您仅更改了传递给函数的值的副本的参数。

要帮助您更好地理解,请考虑以下内容:

#include <stdio.h>
void value(int foo, int bar)
{
    foo = bar;  // changing local copies
}
void pointer(int *foo, int *bar)
{
    *foo = *bar;  // changing the value foo points to to the value bar points to
}
int main(void)
{
    int a = 5;
    int b = 7;
    value(a, b);
    printf("%d, %dn", a, b);  // 5, 7
    pointer(&a, &b);
    printf("%d, %dn", a, b);  // 7, 7
}

我们使用类型int做到了这一点。现在让我们只用int*替换int

#include <stdio.h>
void value(int *foo, int *bar)
{
    foo = bar;  // changing local copies
}
void pointer(int **foo, int **bar)
{
    *foo = *bar;  // changing the value foo points to to the value bar points to
}
int main(void)
{
    int x = 5;
    int y = 7;
    int *a = &x;
    int *b = &y;
    value(a, b);
    printf("%d, %dn", *a, *b);  // 5, 7
    pointer(&a, &b);
    printf("%d, %dn", *a, *b);  // 7, 7  now both point at y
}

所以您知道,这两次都是相同的概念。在第一个示例中,指向int s的值,它们的值是数字,在第二个示例中,指向int* s的值,其值是指针值(&lt;〜〜标准术语,"(。但是机制是相同的

您的程序几乎是正确的,但是您需要在使用crodence和函数的调用时传递函数中的变量地址。

最新更新