我只是在研究自由函数,在其中我们为学生和书定义了自己的数据类型。我必须编写一个代码,通过id和id来查找学生,这是两个函数。在这个函数中,我传递的指针是不同的,但是逻辑是相同的,所以我明白了为什么我们不能编写一个函数并传递想要的东西。我的意思是,当我们通过学生名单时,它将返回学生的索引;当我们通过书目列表时,它将返回该书的书籍索引。我们可以为此使用空指针吗???谢谢大家!!!
int findBookId(Book* booklist,int* bcount,unsigned int* tbid)
{
int i;
for (i=0; i<*bcount; i++)
{
if (booklist[i].id==*tbid)
{
return i;
}
}
return NOT_FOUND;
}
int findStuId(Student* stulist,int* scount,unsigned int* tsid)
{
int i;
for (i=0; i<*scount; i++)
{
if (stulist[i].id==*tsid)
{
return i;
}
}
return NOT_FOUND;
}
是的,您可以使用void*
,但是在取消引用时,您应该知道type
指针的确切信息。
因此,在可以使用函数时,请添加另一个参数:
type = 0 for Books
= 1 for students
然后您的函数变为:
int findId(void* list,int* count,unsigned int* tbid, int type)
{
Book* booklist=NULL;
Student* stulist=NULL;
int i;
if(type===0)
booklist = (Book*) list;
else if(type==1)
stulist = (Student*) list;
else
// Handle this undefined case
// And now use the same type variable to decide which pointer to use to match the values
. . . .
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句