C指针 - Segment故障的解决方案是什么

时间:2018-02-07 13:23:28

标签: c pointers segmentation-fault swap

为什么输出“Segmentation fault(core dumped)

当我运行以下代码时,它会显示Segment fault(core dumped)

#include <stdio.h>

void swap(int *, int *);

int main() {
    int x = 5, y = 10;
    swap(x, y);
    printf("%i\n %i\n", x, y);
}

void swap(int *a, int *b) {
    int s;
    s = *a;
    *a = *b;
    *b = s;
}

1 个答案:

答案 0 :(得分:4)

问题在于行swap(x, y);

您传递的是值而不是地址。你应该有编译器警告。

使用swap(&x, &y);