初学C语言遇到内存written问题,求解!!!!!!!!
具体代码是这样的:
- C/C++ code
#include<stdio.h>void compare(int*v1, int*v2, int*v3, int*v4, int*v5);void swap(int*m1,int*m2);/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~**函数名称:int main(void)**描述:五个数的排序函数**输入参数:无**输出参数:c**返回值:0-成功,1-失败**创建人:牧羊人**创建日期:2012.03.31**备注:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/int main (void){ int a, b, c, d, e, *p1, *p2, *p3, *p4,*p5; printf("Please input 5 nums:\n"); scanf("%d,%d,%d,%d,%d",&a,&b,&c,&d,&e); p1=&a,p2=&b,p3=&c,p4=&d,p5=&e; compare(p1,p2,p3,p4,p5); printf("The sequence is:%d,%d,%d,%d,%d\n", a, b, c, d, e);return 0;}void compare(int*v1, int*v2, int*v3, int*v4, int*v5){ if(*v1>*v2)swap(v1,v2); if(*v1>*v3)swap(v1,v3); if(*v1>*v4)swap(v1,v4); if(*v1>*v5)swap(v1,v5); if(*v2>*v3)swap(v2,v3); if(*v2>*v4)swap(v2,v4); if(*v2>*v5)swap(v2,v5); if(*v3>*v4)swap(v3,v4); if(*v3>*v5)swap(v3,v5); if(*v4>*v5)swap(v4,v5);}void swap(int *m1,int *m2){ int *temp; *temp=*m1; *m1=*m2; *m1=*m2;}
[解决办法]
void swap(int *m1,int *m2)
{
int *temp;
*temp=*m1;
*m1=*m2;///////
*m1=*m2;///////
}
[解决办法]
- C/C++ code
void swap(int *m1,int *m2){ int *temp; *temp=*m1; //这儿没给temp分配空间,你赋值当然出错了 *m1=*m2; *m1=*m2;}void swap(int *m1,int *m2){ int *temp = new int; *temp=*m1; *m1=*m2; *m1=*m2; delete temp;}
[解决办法]
void swap(int *m1,int *m2)
{
int *temp;
*temp=*m1;
*m1=*m2;
*m1=*m2;
}
这个错了
void swap(int *m1,int *m2)
{
int temp;
temp=*m1;
*m1=*m2;
*m1=temp;
}