读书人

C++里的数组作为参数如何传递

发布时间: 2012-04-08 14:38:30 作者: rapoo

C++里的数组作为参数怎么传递?
大家看如下一个冒泡排序,我写成一个函数,数组怎么传递呀? 我这样写有问题。

C/C++ code
#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;


[解决办法]
maopao( A );


int maopao(int *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;

[解决办法]
C/C++ code
 
#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] < < " ";

}

[解决办法]
嗯 用指针就行了.
如果要传整个数组也是可以的,就是封装到struct中传但是效率有问题
[解决办法]
探讨
maopao( A );


int maopao(int *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;


[解决办法]
C/C++ code
#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;} 

读书人网 >C++

热点推荐