C++编程错误

来源:百度知道 编辑:UC知道 时间:2024/06/18 07:08:17
#include<iostream>
using namespace std;
void sort(int *a,int *b,int last){
int temp;
while(*a)
a++;
while(*b)
*a++=*b++;
int i,j;
for(i=1;i<=last;i++){
temp=a[i];
j=i;
while(j>0&&temp<a[j-1]){
a[j]=a[j-1];
j--;
}
a[j]=temp;
}
}int main(){
int a[20]={3,6,0,5,9,13,20,16,10,25};
int b[10]={23,7,1,8,2,19,18,3,4,15};
sort(a,b,20);
for(int i=0;i<20;i++)
cout<<a[i];
return 0;
}
这函数是将两组数据合并,并升序排列。
这样做为什么运行不了

在你的代码的基础上的修改:具体看注释
#include<iostream>
#include <iomanip>
using namespace std;
void sort(int *a,int *b,int last){
int temp;
int *p =a; //这里注意保存a的地址
while(*a)
a++;
while(*b)
*a++=*b++;
int i,j;
a = p; //在这里还原a的起始地址
for(i=1;i<=last-1;i++){ //数组的最大位置为last-1
temp=a[i];
j=i;
while(j>0&&temp<a[j-1]){
a[j]=a[j-1];
j--;
}
a[j]=temp;
}
}int main(){
int a[20]={3,6,22,5,9,13,20,16,10,25}; //要使用while(*a)做判断,只有数组末尾才能有0 (0》6)
int b[11]={23,7,1,8,2,19,18,3,4,15}; //要使用while(*b) ,数组末尾必须有0,让数组宽度大于给定初始值个数即可
sort(a,b,20);
for(int i=0;i<20;i++)
cout<<setw(4)<<a[i] ; //帮你调整格式
return 0;
}

是运算的优先级问题吧。++的优先级比*要高,所以*a++是先运算a++,然后再算*,这样数组就越界了

整数数组,不能拿字符串那样来做的,它可没有'\0'的结束符,你的指针用错了啊,不能那么赋值啊!
我给你盖好了!

#include<iostream>
using n