鱼C论坛

 找回密码
 立即注册
查看: 2076|回复: 6

[已解决]指针交换两个数,这样写为什么会出错?

[复制链接]
发表于 2019-9-14 16:51:27 | 显示全部楼层 |阅读模式
20鱼币
  1. #include <stdio.h>
  2. #include  <stdlib.h>

  3. void swap(int* u,int* v)
  4. {
  5.     int* temp;
  6.     *temp = *u;
  7.     *u = *v;
  8.     *v = *temp;
  9. }

  10. int main()
  11. {
  12.     int x = 5,y = 10;
  13.     printf("x=%d y=%d\n",x,y);
  14.     swap(&x,&y);
  15.     printf("x=%d y=%d\n",x,y);
  16.     return 0;
  17. }
复制代码
最佳答案
2019-9-14 16:51:28
本帖最后由 superbe 于 2019-9-14 19:20 编辑

例如这样,就不会出错了。也就是把 i 的地址给temp.

    int i;
    int *temp;
    temp=&i;
    *temp = *u;
    *u = *v;
    *v = *temp;

最佳答案

查看完整内容

例如这样,就不会出错了。也就是把 i 的地址给temp. int i; int *temp; temp=&i; *temp = *u; *u = *v; *v = *temp;
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-9-14 16:51:28 | 显示全部楼层    本楼为最佳答案   
本帖最后由 superbe 于 2019-9-14 19:20 编辑

例如这样,就不会出错了。也就是把 i 的地址给temp.

    int i;
    int *temp;
    temp=&i;
    *temp = *u;
    *u = *v;
    *v = *temp;
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-9-14 17:48:35 | 显示全部楼层
  1. #include <stdio.h>
  2. #include  <stdlib.h>

  3. void swap(int* u,int* v)
  4. {
  5.     int temp;
  6.     temp = *u;
  7.     *u = *v;
  8.     *v = temp;
  9. }

  10. int main()
  11. {
  12.     int x = 5,y = 10;
  13.     printf("x=%d y=%d\n",x,y);
  14.     swap(&x,&y);
  15.     printf("x=%d y=%d\n",x,y);
  16.     return 0;
  17. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-9-14 17:49:09 | 显示全部楼层
swap函数有问题

  1. void swap(int* u,int* v)
  2. {
  3.     int temp;
  4.     temp = *u;
  5.     *u = *v;
  6.     *v = temp;
  7. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-9-14 19:02:16 | 显示全部楼层

我知道这样写,但是像我上面那样写,为什么会报错呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-9-14 19:05:28 | 显示全部楼层

那为什么我上面那么写会报错呢,我知道上面的代码会报错呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-9-14 19:12:38 | 显示全部楼层
本帖最后由 superbe 于 2019-9-15 16:11 编辑

你代码里temp是一个指针,但没有初始化,也就是説它的值(是一个地址)是未知的,而这句却要给它指向的内存赋值*temp = *u;
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-7-4 00:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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