c - 在 c 中交换两个数字时出现段错误(核心已转储)

标签 c

这是代码

#include <stdio.h>
void swap(int *a,int *b)
{
    int *tmp;
    *tmp=*a;
    *a=*b;
    *b=*tmp;
}

void main()
{
    int i,j;
    printf("Enter any number\n");
    scanf("%d",&i);
    printf("Enter another number\n");
    scanf("%d",&j);
    printf("Numbers before swap\n");
    printf("value of i : %d\n",i);
    printf("value of j : %d\n",j);
    swap(&i,&j);
    printf("Numbers after swap\n");
    printf("value of i : %d\n",i);
    printf("value of j : %d\n",j);
}

上面一个是我的代码,它工作正常但是当输出打印在控制台上时它会给出段错误(核心转储) 这是 o/p

abc:~/Desktop/C$ ./a.out

Enter any number

34

Enter another number

54

Numbers before swap

value of i : 34

value of j : 54

Numbers after swap

value of i : 54

value of j : 34

Segmentation fault (core dumped)

最佳答案

您正在使用未初始化的 tmp(您声明为指针)。

尝试

int tmp;
tmp=*a;
*a=*b;
*b=tmp;

关于c - 在 c 中交换两个数字时出现段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29726346/

相关文章:

c - 使用 libxml2 的 XML 注释

c - 为什么说 vp 和 pf 都在结构节点中时未声明?

c# - DllImport 在 Windows XP SP3 上失败,但在 Windows 7 上有效

c - 期待一份声明

c++ - 在哪里可以找到 C++ 的 ZwCreateFile 示例?

c - 如何从 Win32 API 获取打印机制造商和型号?

c - 在 Gtk+ 中,一个键盘事件会禁用所有其他键盘事件

c - 为什么 gcc 不为 int 和 char 产生类型不匹配警告?

c - 如何连接到 GSS 中的多服务器机器?

c - 在C中是否有充当“实例方法”的功能的术语?