数据结构线性表方法参数问题
#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
#define MAXSIZE 20
typedef int ElemType;
typedef struct{
ElemType data[MAXSIZE];
int length;
}SqList;
Status GetElem(SqList L, int i, ElemType *e)
{
if(L.length == 0 || i < 1 || i > L.length)
return ERROR;
*e = L.data[i-1];
return OK;
}
Status ListInsert(SqList *L, int i, ElemType e)
{
int k;
if(L->length == MAXSIZE)
return ERROR;
if(i < 1 || i > L->length+1)
return ERROR;
if( i <= L->length)
{
for(k = L->length-1; k >= i-1; k--)
L->data[k+1] = L->data[k];
}
L->data[i-1] = e;
L->length++;
return OK;
}
在
Status GetElem(SqList L, int i, ElemType *e)中参数是用L,e,而在
Status ListInsert(SqList *L, int i, ElemType e)中却是*L,e,请问为什么要选择这两种方式?有什么区别?具体使用中如何选择?
[解决办法]
传值和传引用的区别。
GetElem()函数第一个参数是传值,这样传进的实参是原L的一个拷贝,也就是在这个函数里对L的任何操作不会改变原L的数据,第二个参数是传引用,会改变e的值。
ListInsert()函数道理是一样的。关键是你是否要改变函数参数的值,再来选择哪种方式。