我写的C函数遇到一个从来没遇到的问题LocateElem_Sq(SqList L, ElemType e, Status ( *compare) (ElemType, ElemType))
这是书上定义的线性表顺序表原型int LocateElem_Sq(SqList L, ElemType e,
Status ( *compare) (ElemType, ElemType))
想当于LocateElem_Sq (L,e,compare());
;首先这是C代码C的库中没有compare()函数,按书上的意思也是自定义,
我在没定义compare()函数前能编译成功,但是一在main()中调用我就不会了,
然后自己定义了一个compare()函数,还是在main()中用不来
我若这么调用result = LocateElem_Sq(L, 5, compare(0,0));
它说 error C2664: “LocateElem_Sq” : 不能将参数 3 从“int”转换为“Status (__cdecl *)(ElemType,ElemType)”
我若这么调用result = LocateElem_Sq(L, 5, &compare(0,0));
它说 error C2102: “&”要求 l 值
下面伟上源码请大虾帮小弟一下,其它人也可以发点言,小弟我当散分~! 曾经对用程序做数学题目以及算法因枯燥不感兴趣,当我做大型开发时才知道程序的灵魂还是算法,不得不反功啊,再学数据结构和算法~~!希望那些初学者不要向在下学习
// Linear-list.cpp : 定义控制台应用程序的入口点。
//Copyrith (C) 2005.12 By Renyi
#include "stdafx.h"
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
//Status 是函数反回类型,其值是函数结果状态代码//
typedef int Status;
//ElemType根根实际需要的类型定义,暂设为int
typedef int ElemType;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef struct {
ElemType *elem;
int length;
int listsize;
}SqList;
int compare(ElemType a,ElemType b) {
if (a + b == 10)
return TRUE;
else
return FALSE;
}
Status InitList_Sq(SqList &L) {
//构造一个空的顺序线性表L
L.elem = (ElemType *) malloc( LIST_INIT_SIZE * sizeof(ElemType));
if ( !L.elem) exit (OVERFLOW ); //存储空间分配失败
L.length = 0; //空表长度为0
L.listsize = LIST_INIT_SIZE; //初始存储容量
return OK;
}//InitList_Sq
int LocateElem_Sq(SqList L, ElemType e,
Status ( *compare) (ElemType, ElemType)) {
//在顺序线性表L中查找第1个值与e满足compare()的元素的位序
//若找到,则返回其在L中的位序,否则返回0
int i =1; //i初使值为第一个元素的位序
ElemType *p = L.elem; //p初使值为第一个元素的存储位置
while ( i<= L.length && !(*compare) (*p++, e))
++i;
if ( i <= L.length) return i;
else return 0;
}//LocateElem_Sq
Status ListInsert_Sq(SqList &L, int i, ElemType e) {
//在顺序线性表L中第i个位置之前插入新的元素e, 1<=i<=ListLength_Sq(L) +1
ElemType *p,*q; //临时局部变量
if ( i < 1 || i > L.length+1) //判断有关参数的合理性:i值不合法
return ERROR;
if ( L.length >= L.listsize ) { //存储空间不够需要分配
L.elem = (ElemType *) realloc( L.elem, (L.listsize + LISTINCREMENT)
*sizeof(ElemType));
if (!L.elem) exit(OVERFLOW); //空间分配失败
L.listsize += LISTINCREMENT;
}//endif
q = &L.elem[i-1]; //q为插入位置
for ( p = &(L.elem[L.length-1]); p >= q; --p)
*(p + 1) = *p; //插入位置及以后的元素右移
*q = e; //插入e
++L.length; //表长增1
return OK;
}//ListInsert_Sq修正函数by Renyi
Status ListPrint_Sq(SqList &L) {
//输出一个顺序表
ElemType *p;
if (!L.elem) { //此条件判断有误现在没有办法改正因能力有限
printf("You pass a Null linear-list");
return ERROR;
}
if (L.length == 0) {
printf("You pass a empty linear-list.\n");
return OK;
}
//原为:p = &(L.elem[0]);
p = L.elem;
printf("Your current linear-list is:\n");
for (int i = 0; i < L.length; i++) {
if ( i%10 == 0)
printf("\n");
printf("%d ",*(p+i));
}
printf("\n");
return OK;
}//ListPrint_Sq
int _tmain(int argc, _TCHAR* argv[])
{
SqList L;
int result;
InitList_Sq(L);
for (int i =0; i <= LIST_INIT_SIZE; i++)
ListInsert_Sq(L, i, i);
ListPrint_Sq(L);
result = LocateElem_Sq(L, 5, &compare(0,0));
return 0;
}