鱼C论坛

 找回密码
 立即注册
查看: 3341|回复: 1

刚学到指针,有点问题求教

[复制链接]
发表于 2013-7-21 20:50:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
输入三个数,按大小顺序输出这三个数,自己写了一段程序,测试了一下,没问题
#include <stdio.h> void main()
{
//void swap(int *x, int *y);
int a, b, c, *p1, *p2, *p3;
int t;
printf("Input 3 No.s:\n"); scanf("%d %d %d", &a, &b, &c); p1 = &a;
p2 = &b;
p3 = &c; if (*p1 < *p2)
{
//swap(p1, p2);
t = p1;
p1 = p2;
p2 = t;
}
if (*p1 < *p3)
{
//swap(p1, p3);
t = p1;
p1 = p3;
p3 = t;
}
if (*p2 < *p3)
{
//swap(p2, p3);
t = p2;
p2 = p3;
p3 = t;
} printf("a = %d, b = %d, c = %d\n", a, b, c);
printf("*p1 = %d, *p2 = %d *p3 = %d\n", *p1, *p2, *p3);
}
/*
void swap(int *x, int *y)
{
int *t;
t = x;
x = y;
y = t;
}*/
a,b,c的值都没有改变。但我想把程序分成两个函数,却出了点问题。
#include <stdio.h> void main()
{
void swap(int *x, int *y);
int a, b, c, *p1, *p2, *p3;
int t;
printf("Input 3 No.s:\n"); scanf("%d %d %d", &a, &b, &c); p1 = &a;
p2 = &b;
p3 = &c; if (*p1 < *p2)
{
swap(p1, p2);
/* t = p1;
p1 = p2;
p2 = t;*/
}
if (*p1 < *p3)
{
swap(p1, p3);
/* t = p1;
p1 = p3;
p3 = t;*/
}
if (*p2 < *p3)
{
swap(p2, p3);
/* t = p2;
p2 = p3;
p3 = t;*/
} printf("a = %d, b = %d, c = %d\n", a, b, c);
printf("*p1 = %d, *p2 = %d *p3 = %d\n", *p1, *p2, *p3);
} void swap(int *x, int *y)
{
int *t;
t = x;
x = y;
y = t;
}
a,b,c的值都被改变了。
怎么把前面的程序改成多个函数,程序功能不变?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2013-7-22 17:51:12 | 显示全部楼层

  1. #include <stdio.h>
  2. void main()
  3. {
  4.          void swap(int *x, int *y);
  5.          int a, b, c, *p1, *p2, *p3;
  6.          printf("Input 3 No.s:\n"); scanf("%d %d %d", &a, &b, &c);
  7.          p1 = &a;
  8.          p2 = &b;
  9.          p3 = &c;
  10.          if (*p1 < *p2)
  11.          {
  12.                  swap(p1, p2);
  13.                  /* t = p1;
  14.                  p1 = p2;
  15.                  p2 = t;*/
  16.          }
  17.          if (*p1 < *p3)
  18.          {
  19.                  swap(p1, p3);
  20.                  /* t = p1;
  21.                  p1 = p3;
  22.                  p3 = t;*/
  23.          }
  24.          if (*p2 < *p3)
  25.          {
  26.                  swap(p2, p3);
  27.                  /* t = p2;
  28.                  p2 = p3;
  29.                  p3 = t;*/
  30.          }
  31.          printf("a = %d, b = %d, c = %d\n", a, b, c);
  32.          printf("*p1 = %d, *p2 = %d *p3 = %d\n", *p1, *p2, *p3);
  33. }
  34. void swap(int *x, int *y)
  35. {
  36.          /*
  37.          int *t;
  38.          t = x;
  39.          x = y;
  40.          y = t;
  41.          */
  42.          int t;
  43.          t = *x;
  44.          *x=*y;
  45.          *y=t;
  46. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-18 21:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表