c - 交换程序问题,程序崩溃

标签 c pointers

我正在尝试制作一个扫描 3 个整数的程序,然后将它们传递给一个按这种方式对它们进行排序的函数 - 最大的数字将在“num3”,第二个将在“num2”,最小的将位于“num1”,但由于某种原因程序在进入排序功能时崩溃。

#include <stdio.h>
#include <stdlib.h>

void swap(int* a, int* b);
void changer(int* num1, int* num2, int* num3);

int main()
{
    int num1 = 0;
    int num2 = 0;
    int num3 = 0;

    printf("Please enter your value for 'num1': ");
    scanf("%d", &num1);
    getchar();

    printf("Please enter your value for 'num2': ");
    scanf("%d", &num2);
    getchar();

    printf("Please enter your value for 'num3': ");
    scanf("%d", &num3);

    printf("\nYour nums before- \n");
    printf("num1 == %d\n", num1);
    printf("num2 == %d\n", num2);
    printf("num3 == %d\n", num3);

    changer(&num1, &num2, &num3);

    printf("\nYour nums after- \n");
    printf("num1 == %d\n", num1);
    printf("num2 == %d\n", num2);
    printf("num3 == %d\n", num3);

    system("PAUSE");
    return 0;
}

void changer(int* num1, int* num2, int* num3)
{
    if (*num1 > *num3)
    {
        swap(*num3, *num1);
    }
    else if (*num1 > *num2)
    {
        swap(*num1, *num2);
    }

    if (*num2 > *num3)
    {
        swap(*num3, *num2);
    }
}

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

最佳答案

当您将指针传递给 swap() 时,您不应该取消引用它们,因为它需要 int * 而您将传递 int导致未定义的行为,在您的情况下会导致崩溃。编译器应该对不兼容的参数发出警告。

改变每一次出现

swap(*num1, *num2);
/*   ^      ^ remove these */

swap(num1, num2);

关于c - 交换程序问题,程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36098476/

相关文章:

c - 在指针数组中写入指针

C++11 char 数组初始化和字符串文字

C++ Qt 表达式 : _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) error

iphone - OpenGL ES - glImageProcessing - 移除纹理

从 C 调用 Haskell,得到 "multiple definition of main"链接器错误

c - C 中字符串数组的值增加

C++ 错误 C2819 : type 'List' does not have an overloaded member 'operator ->'

c - unistd.h 的 `l` 中的 `lseek` 是什么意思?

c - 为什么这段代码的结果不一样?

c - 在 C 中使用多个名称引用变量