C中抽象数据类型代码的问题[重复]

z9gpfhce  于 2023-02-18  发布在  其他
关注(0)|答案(2)|浏览(145)
    • 此问题在此处已有答案**:

How do you compare structs for equality in C?(11个答案)
昨天关门了。
我定义了以下类型:

#define NAME_LENGTH_LIMIT 25
#define LNULL (-1)
#define MAX 1000

typedef char tParticipantName[NAME_LENGTH_LIMIT];
typedef int tNumVotes;
typedef bool tEUParticipant;

typedef struct tItemL {
    tParticipantName participantName;
    tNumVotes numVotes;
    tEUParticipant EUParticipant;
} tItemL;
typedef int tPosL;
typedef struct tList {
    tItemL data[MAX];
    tPosL lastPos;
} tList;

下面的代码会产生问题,因为它需要读取一个字符,但当我插入一个字符时,我收到了这个错误-〉错误:binary ==的操作数无效(具有"tItemL"和"tItemL")。

tPosL findItem(tItemL d, tList L) {
    tPosL t;
    if (L.lastPos == LNULL) {
        return LNULL;
    } else {
        t = first(L); //p=0;
        while (t != LNULL && (L.data[t] == d)) { //error in this line
            t = next(t, L);
        }
        if (L.data[t] == d) return t;//error in this line 
        else return LNULL;
    }
}

我不知道如何解决这个问题

ef1yzkbh

ef1yzkbh1#

if (L.data[t] == d)

这里L.data[t]d的计算结果为struct s。
不能使用==运算符比较两个struct是否相等。
您需要分别比较每个成员。

xzabzqsa

xzabzqsa2#

1.你应该把指针传递给这个大的结构体,而不是结构体本身,因为你每次调用这个函数时都要复制整个结构体。
1.在typedef后面隐藏标准类型。
1.不要在typedef后面隐藏数组

typedef struct tItemL {
    char participantName[NAME_LENGTH_LIMIT];
    int numVotes;
    bool EUParticipant;
} tItemL;

typedef int tPosL;
typedef struct tList {
    tItemL data[MAX];
    tPosL lastPos;
} tList;

int compare(const tItemL *i1, const tItemL *i2)
{
    return strcmp(i1 -> participantName, i2 -> participantName) &&
           i1 -> numVotes == i2 -> numVotes &&
           i1 -> EUParticipant && i1 -> EUParticipant;
}

int findItem(tItemL *d, tList *L) {
    int t = -1;
    if (L -> lastPos == LNULL) {
        return LNULL;
    } else {
        t = first(L); //p=0;
        while (t != LNULL && compare(&L -> data[t], d)) { //error in this line
            t = next(t, L);
        }
        if (compare(&L -> data[t], d)) return t;//error in this line 
        else return LNULL;
    }
}

您需要更改其他函数以获取非struct的指针

相关问题