|
-
March 15th, 2007, 11:01 PM
#1
Re-use in C?
Is it possible to reuse the functions in C for different data types in run time?
For example: I have functions to process link list: T represent any data types:
Code:
typedef struct {
char data[10];
void* p_next;
int index;
} *pDateStruct;
typedef struct {
char data[2];
void* p_next;
int index;
} *pRecipeStruct;
T NewDateStruct(void)
{
T Newrptlst = NULL; /* Pointer on the new sructure */
/* create the new structure */
Newrptlst = (T) malloc(sizeof *Newrptlst);
if (!Newrptlst)
{
Newrptlst = NULL;
return Newrptlst;
}
/* Initialize the new structure */
memset (Newrptlst, 0, sizeof *Newrptlst);
Newrptlst->p_next = NULL;
Newrptlst->index = -1;
return Newrptlst;
}
T AddDateStruct(T *List)
{
T CurRptlst= NULL; /* Pointer on the current record */
T NewRptlst= NULL; /* Pointer on the next record */
T LatRptlst= NULL; /* Pointer on the last record */
if (*List == NULL) {
*List= NewDateStruct();
return *List;
} else {
CurRptlst= *List;
/* search the last record into the list */
while (CurRptlst != NULL && CurRptlst->index >= 0) {
LatRptlst = CurRptlst;
CurRptlst= (T) CurRptlst->p_next;
}
/* if the last struct is not NULL and its index is < 0, means it is created before and we can re-use it, so no need to allocate new memory */
if(CurRptlst != NULL && CurRptlst->index < 0)
{
return CurRptlst;
}
NewRptlst= NewDateStruct();
LatRptlst->p_next=NewRptlst;
return NewRptlst;
}
}
int DelDateStruct(T *List)
{
int ResCode = 0; /* Internal step result code */
T CurList = NULL; /* Pointer on the first record to be deleted*/
T NextList = NULL; /* Pointer on the next record */
CurList = *List;
while (CurList != NULL) {
NextList = (T) CurList->p_next;
free(CurList);
CurList= NextList;
}
if (ResCode == 0)
*List = NULL;
return ResCode;
}
To make it work or compile successfully, I have to add
Code:
#define T pDateStruct
or
Code:
typedef pDateStruct T;
Now the issue comes, I want to reuse these functions on pRecipeStruct also, is that possible in C?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|