关于Dev c++工程的建立

将随机函数产生的数排序一下。
这是用工程做的^O^
main.c中
#include <iostream>
#include<iomanip>
#include<ctime>
#include<cstdlib>
#include"sort.c"
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
int a[20];
srand(time(0));
for(int i=0;i<20;i++)
a[i]=rand()%100;
sort(a);
for(int i=0;i<20;i++)
cout<<a[i]<<' ';
return 0;
}

sort.c中
void sort(int *b)
{
int i,j,t;
for(i=0;i<19;i++)
for(j=i+1;j<20;j++)
{
if(b[i]<b[j])
{
t=b[i];
b[i]=b[j];
b[j]=t;
}
}
}
好像是sort文件在main文件的引用出了问题,请问应该怎么改哈?

第1个回答  推荐于2016-08-07
你不能这样引用的,你的sort()函数的参数是一个变量指针,而你的数组a可以理解为一个常量指针,所以会报错,正确的方式应该是先定义一个指针指向a数组,然后调用sort();
int *c=a;
sort(c);
for(int i=0;i<20;i++)
cout<<c[i]<<' ';
return 0;
就像这样。
下面给你改了下代码(可以运行得出结果)
#include <iostream>
#include<iomanip>
#include<ctime>
#include<cstdlib>
using namespace std;
void sort(int *b);
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
int a[20];
srand(time(0));
for(int i=0;i<20;i++)
a[i]=rand()%100;
int *c=a;
sort(c);
for(int i=0;i<20;i++)
cout<<c[i]<<' ';
return 0;
}
void sort(int *b)
{
int i,j,t;
for(i=0;i<19;i++)
for(j=i+1;j<20;j++)
{
if(b[i]<b[j])
{
t=b[i];
b[i]=b[j];
b[j]=t;
}
}
}本回答被提问者和网友采纳
相似回答