#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getmax(int a, int b)
{
if(a>b)
{
return a;
}else
{
return b;
}
}
void swap(void * a, void * b)
{
void * tmp;
int la=sizeof(a);
int lb=sizeof(b);
int max=getmax(la,lb);
void * t=(void *)malloc(max);
if(t ==NULL)
{
printf("%s\n","错误");
exit(0);
}
memcpy(t,a,max);
memcpy(a,b,max);
memcpy(b,t,max);
printf("%d\n",sizeof(a));
printf("%d\n",sizeof(b));
printf("%d\n",max);
free(t);
}
int main()
{
char * str="123";
char * str2="456";
swap((void *)str,(void *)str2);
printf("%s\n",str);
printf("%s\n",str2);
}
这样申请的 2 个字符串,实际上是 2 个 指针 str 和 str2 分别指向了 2 个字符串常量。
所以当你执行这段代码的时候:
均会报错,因为你试图去修改字符串常量。
另外如果你给出的 2 个字符串长度不一样,你的程序一样会出错,这个留给你自己思考解决吧