你更喜欢哪个代码,为什么?使用指针交换值的程序



这是一个使用指针交换两个数字的程序。

#include<stdlib.h>
#include<stdio.h>
void swap(int *x, int *y){
int temp = *x;
*x = *y;
*y = temp; 
}
int main(int argc, char const *argv[])
{
int *a = (int *) malloc(sizeof(int));
int *b = (int *) malloc(sizeof(int));
*a =1;
*b =2;
printf("Nos are: %i %in", *a, *b);
swap(a,b);
printf("Swapped: %i %in", *a, *b);
free(a);
free(b);
return 0;
}

你喜欢这个还是,

#include<stdlib.h>
#include<stdio.h>
void swap(int *x, int *y){
int temp = *x;
*x = *y;
*y = temp; 
}
int main(int argc, char const *argv[])
{
int a= 1;
int b= 2;
printf("Nos are: %i %in", a, b);
swap(&a,&b);
printf("Swapped: %i %in", a, b);
return 0;
}

哪一个在编程标准方面更好?或者你更喜欢哪一个?(也请给出一些理论上的解释)两个代码的输出是相同的,即交换并返回2 1

我会
首选第一种情况,如果我交换一些重数据,让我们说一些struct x,所以我们传递struct的地址,这是一个固定的大小取决于系统。

对于正常数据,如intchar等,首选第二种情况。不需要

我不喜欢使用指针的swap函数。这个任务最好由宏来完成:

#include <stdio.h>
#define SWAP(a,b,type) do{type c__c__c; c__c__c = (a); (a) = (b); (b) = c__c__c;}while(0)
struct s
{
int a;
char x[100];
double w[100];
};
int main()
{
double a = 5.0, b = 6.0;
int c = 5, d = 6;
struct s x = {.a = 1},y = {.a = 2};
SWAP(a, b, double);
SWAP(c, d, int);
SWAP(x, y, struct s);

printf("%f %fn", a, b);
printf("%d, %dn", c, d);
printf("%d, %dn", x.a, y.a);
return 0;
}

和代码将非常有效。你也不必为每种类型都写几十个函数。

当然你可以写"generic"交换功能

void *swap(void *a, void *b, size_t size)
{
unsigned char temp[size];
memcpy(temp, a, size);
memcpy(a, b, size);
memcpy(b, temp, size);
return a;
}