Menu Close

C 语言练习:利用指针交换两个整数

请看下列程序

#include<stdio.h>
 
//Swap function to swap 2 numbers
void swap(int *num1, int *num2) {
   int temp;
   //Copy the value of num1 to some temp variable
   temp = *num1;
 
   //Copy the value of num2 to num1
   *num1 = *num2;
 
   //Copy the value of num1 stored in temp to num2
   *num2 = temp;
}
 
int main() {
   int num1, num2;
 
   //Inputting 2 numbers from user
   printf("\nEnter the first number : ");
   scanf("%d", &num1);
   printf("\nEnter the Second number : ");
   scanf("%d", &num2);
 
   //Passing the addresses of num1 and num2
   swap(&num1, &num2);
 
   //Printing the swapped values of num1 and num2
   printf("\nFirst number  : %d", num1);
   printf("\nSecond number : %d", num2);
 
   return (0);
}

结果

除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in 数组和指针

Related Posts