In order to work with the data structures defined in the GDS library, your structure (which we shall call an object from now on) must be defined in a certain way. In this article I will provide you with a simple example on how to define such an object.
The first thing that you must do is the structure declaration:
typedef struct
{
int value;
}Integer;
The structure above is a simple wrapper for a integer, containing only one member who shall represent the value of the integer.The object must implement the following operations defined by the Interface data structure:
| Operation | Description |
| Copy | Creates a hard copy of the object |
| Compare | Compares an object with another object of the same type. |
| Destroy | Frees the memory allocated for the current object |
Integer* Integer_Copy(const Integer* integer)
{
Integer *i = NULL;
i = malloc(sizeof(Integer));
i->value = integer->value;
return i;
}
Integer* Integer_Destroy(Integer* integer)
{
free(integer);
return NULL;
}
int Integer_Compare(const Integer* i1, const Integer* i2)
{
return (*(int*)(i1->value) - *(int*)(i2->value));
}
As you probably observed in the int Integer_Compare(const Integer *i1, const Integer *i2) the member value of the Integer object uses a double cast. This must be done because the interface functions have void* parameters.Also, I consider good practice to define an "constructor"-like function for the structure:
Integer* Integer_Create(int value)
{
Integer *i = NULL;
i = malloc(sizeof(Integer));
i->value = value;
return i;
}
To see the full source check the following links:
No comments:
Post a Comment
Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!