所以,我遇到了一个小问题。我正在尝试构建一个哈希表,但我不断收到一条错误消息,提示“从不兼容的指针类型返回”。我知道这意味着什么,但我不知道为什么我的代码不起作用。我正在寻找为什么我的代码不起作用的解释。为什么它不将数组识别为指针?
我正在制作一个指向哈希表结构的指针数组。 (外部链接) (我知道我的代码可能真的很烂><我还在学习!)
struct hashTBL {
char *userID;
char *password;
struct hashTBL *next;
};
typedef struct hashTBL Tbl;
typedef struct hashTBL* TblPTR;
TblPTR createHashTBL(int size)
{
char *userID;
char *password;
int i;
TblPTR hashArray[size];
FILE* fpData;
char *fileName = "encrypted.txt";
fpData = openReadFile(fileName);
TblPTR T = NULL;
while((fscanf(fpData, "%s", userID)) != EOF)
{
fscanf(fpData, "%s", password);
i = hash(userID, size);
if(hashArray[i] != NULL)
{
TblPTR H = hashArray[i];
while(H != NULL)
{
T = H;
H = H->next;
}
H = newPTR(userID, password, T);
}
else
{
hashArray[i] = newPTR(userID, password, T);
}
}
closeFile(fpData);
return &hashArray;
}
TblPTR newPTR(char *userID, char *password, TblPTR T)
{
TblPTR H = (TblPTR)malloc(sizeof(Tbl));
if(T != NULL) T->next = H;
H->userID = userID;
H->password = password;
H->next = NULL;
return H;
}
最佳答案
你至少有两个问题。
首先,您的 createHashTBL()
函数被定义为返回一个 TblPTR
对象,并且您返回一个指向数组的指针 TblPTR
对象。您应该更改函数类型以匹配您正在尝试的返回类型,或者返回正确类型的对象。
其次,您的 hashArray
在 createHashTBL()
函数中进行堆栈分配,这意味着您无法返回指向它的指针。当你的函数返回时它会消失。您应该尝试使用 malloc()
分配数组或让调用者提供指向预分配数组的指针。
关于c - 返回指向结构指针数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4887647/