C 指针奇怪的行为

标签 c pointers

我无法理解为什么会这样:

int main() {
    int test = 4;
    int *bar = &test;
    int **out = &bar;
    printf("%d\n", **out);
    return 0;
}

但这不是:

void foo(int *src, int **out) {
    out = &src;
}

int main() {
    int test = 4;
    int *bar = &test;
    int **out;
    foo(bar, out);
    printf("%d\n", **out);
    return 0;
}

第二个片段抛出“段错误”。在我看来,他们似乎做同样的事情。有人可以解释一下吗?

编辑:(根据答案更新代码):

void foo(int *src, int **out) {
    out = &src;
}

int main() {
    int test = 4;
    int *bar = &test;
    int *out;
    foo(bar, &out);
    printf("%d\n", *out);
    return 0;
}

那为什么不行呢?

解决了:(我不得不想清楚我真正想做的是什么),结果是这样的:

void foo(int *src, int **out) {
    *out = src;
}

int main() {
    int test = 4;
    int *bar = &test;
    int *out;
    foo(bar, &out);
    printf("%d\n", *out);
    return 0;
}

最佳答案

在第二种情况下,main 中的变量 out 不受 foo 内部赋值的影响。

在您的编辑中,您需要将 foo 分配给其中的 out 指向的内容:

*out = src;

关于C 指针奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41404072/

相关文章:

c - 用于在二叉树中查找(有序)节点后继的代码中的段错误

arrays - 不计算空格计算字符串长度

C - 未知数字中的最大数字

c++ - 必须调用对非静态成员函数的引用

c - C 中的嵌套结构和取消引用指针

c - C : tee command produces empty file 中的管道

c - 储存二十一点手牌的最佳方式是什么?

c - 如何释放二维数组?

swift - vDSP_zrvmul 不返回任何结果(或全零)

c - 为什么输出是 2,0 而不是 2,3?