I have this ordered List structure that has a structure that has two members, an array of type Titem and an int counter. Now, this List can take any type and arrange it in ascending order. Suppose, i decided to typedef char Titem, then the array contains characters, if i typedef int Titem, then the array contains integers. Now, I have a structure somewhere with the type Tage;
how do i make the Ordered List identify it. when i did typedef Tage Titem, it complains. Where should I insert it in the OList header file? Or is there a way to do forward declarations like it is done in C++ in C?
#ifndef OLIST_H
#define OLIST_H
/*typedef char Titem; here, i typedef char to Titem, though commented out..
how do i do similar thing for the Tage datatype i have?
*/
#define MAX 10
typedef struct {
int count;
Titem array[MAX]; //Titem is not typedefed yet, so error..
} TOrderedList;
void initialize_list(TOrderedList *list);
int insert_item(TOrderedList *list, Titem item);
int retrieve_ith(const TOrderedList *list, int i, Titem *item);
int number_of_items(const TOrderedList *list);
int list_empty(const TOrderedList *list);
#endif
Or is there a way to do forward declarations like it is done in C++ in C?
No, You cannot use Forward declaration here.
Rationale for why Forward declaration will not work:
When you use forward declaration of any type, the compiler does not know the composition of it nor the members inside it, the compiler only knows that the type exists. Thus, it is an Incomplete type for the compiler. With Incomplete types , One cannot create objects of it or do anything which needs the compiler to know the layout of the type or more than the fact that it is just an type. Since pointers to all objects need just the same memory allocation, You can use the forward declaration when just reffering to types as a pointer.
However, here the compiler needs to know the layout and size of the type
Titemsince it needs to know how much memory to allocate while creating an array, hence forward declaring the typeTitemwill not work.Solution:
You need to let the compiler know of the layout of
Titemand the way to do that is to include the header defining the typeTitemin the source file where you create the array,