C++里的数组作为参数怎么传递?
大家看如下一个冒泡排序,我写成一个函数,数组怎么传递呀? 我这样写有问题。
#include <conio.h>#include <iostream.h>#pragma hdrstop//---------------------------------------#pragma argsused#define N 9 //定义数组元素个数int maopao(int A[]);int main(int argc, char* argv[]){ int A[9] = {19,23,79,33,13,68,99,36,28}; maopao( A[] ); return 0;}int maopao(int A[]){ int a[] = A[]; int i, j, temp; cout << "排序前:"; for(i=0; i<N; i++) cout << a[i] << " "; for(i=0; i<N; i++) { for(j=i+1; j<N; j++) { if(a[i]>a[j]) { temp = a[j]; a[j] = a[i]; a[i] = temp; } } } cout << "\n排序后:"; for(i=0; i<N; i++) cout << a[i] << " "; getch(); return 0;
#include <conio.h>
#include <iostream>
//#pragma hdrstop
using namespace std;
//---------------------------------------
#pragma argsused
#define N 9
//定义数组元素个数
void maopao(int A[]);
int main(int argc, char* argv[])
{
int A[9] = {19,23,79,33,13,68,99,36,28};
maopao(A);//调用的时候直接用数组名就可
getch();
return 0;
}
void maopao(int A[])
{
int *a;//此处用指针
a=A;//把数组的首地址赋给a,a就是一个数组了
int i, j, temp;
cout < < "排序前:";
for(i=0; i <N; i++)
cout < < a[i] < < " ";
for(i=0; i <N; i++)
{
for(j=i+1; j <N; j++)
{
if(a[i]>a[j])
{
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
cout < < "\n排序后:";
for(i=0; i <N; i++)
cout < < a[i] < < " ";
}
#include <conio.h>#include <iostream>using namespace std;//#pragma hdrstop//#pragma argsused#define N 9 //定义数组元素个数int maopao(int A[]);int main(int argc, char* argv[]){ int A[9] = {19,23,79,33,13,68,99,36,28}; maopao( A ); return 0;}//数组作为参数传递时,其实传递的就是指针。int maopao(int A[]){ int * a = A; //数组的首地址可以用指针来表示 int i, j, temp; cout << "排序前:"; for(i=0; i<N; i++) cout << a[i] << " "; for(i=0; i<N; i++) { for(j=i+1; j<N; j++) { if(a[i]>a[j]) { temp = a[j]; a[j] = a[i]; a[i] = temp; } } } cout << "\n排序后:"; for(i=0; i<N; i++) cout << a[i] << " "; getch(); return 0;}