简单的交换功能...为什么不进行一次交换? [英] Simple swap function...why doesn't this one swap?

查看:127
本文介绍了简单的交换功能...为什么不进行一次交换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的新手,但仍在尝试掌握指针的概念.我知道如何编写一个有效的交换函数...我更担心为什么这个特定的交换函数不起作用.

I'm new to C and still trying to grasp the concept of pointers. I know how to write a swap function that works...I'm more concerned as to why this particular one doesn't.

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

int main()
{
 int x = 5, y = 10;
 int *a = &x, *b = &y;
 swap(a, b);
 printf("%d %d\n"), *a, *b);
}

推荐答案

在交换功能中缺少*.试试:

You're missing *s in the swap function. Try:

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

这样,您将交换指针指向指向int,而不仅仅是交换指针.

That way, instead of just swapping the pointers, you're swapping the ints that the pointers are pointing to.

这篇关于简单的交换功能...为什么不进行一次交换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆