主代码

#include <stdio.h>
#include "mylib.h"
int main()
{
    int test1 = 0;
    int test2 = 0;
    printf("Input 2 Integers\n");
    scanf_s("%d%d",&test1,&test2);
    error_swap(test1,test2);
    int test_sum = int_sum(test1, test2);
    printf("test1=%d test2=%d test_sum = %d\n", test1, test2,test_sum);
    //原因解析:
    //整型变量test1和test2将值传递入mylib.h中error_swap函数,并没有调用其实参
    //函数处理的仅为在内存中的值,故无法隐藏实参test1或test2的值
    //函数运行处理完毕后,并没有给出任何返回值(void)值便直接消失,无效操作
    point_swap(&test1, &test2);
    printf("test1=%d test2=%d test_sum = %d\n", test1, test2, test_sum);
}

Mylib.h库


#ifndef MYLIB_H
#define MYLIB_H
int int_sum(int a,int b)//整型变量求和函数
{
    return a + b;
}
void error_swap(int x, int y)//变量值交换函数-错误
{

    int temp = y;

    y = x;

    x = temp;
}
void point_swap(int* point1, int* point2)//变量值交换函数-正确
{
    //通过交换地址 实现交换值的效果 实际上值依然在内存的相应位置 未发生改变

    int swap_point_t = *point2;

    *point2 = *point1;

    *point1 = swap_point_t;
}
#endif

运行结果

c7.png

最后修改:2022 年 10 月 29 日
如果觉得我的文章对你有用,只需评论或转发支持,谢绝投喂!