Reputation: 73
I have a program that creates, inserts into, deletes from and destroys priority queue in C. Everything works fine, but I have a task to make it easier for user to create the queue.
int Error;
PrQueue* q1= create(&Error);
PrQueue* q2 = create(&Error);
PrQueue* q3 = create(&Error);
Here is how I create the priority queue.
PrQueue* create(int* Error)
{
PrQueue* Meta = (PrQueue*)malloc(sizeof(PrQueue));
if(Meta == NULL)
{
*Error = 1;
return NULL;
}
Meta->NrOfItems = 0;
Meta->Head = NULL;
*Error = 0;
return Meta;
}
That's the function
typedef struct Element
{
int Data;
int Priority;
struct Element *Next;
struct Element *Prev;
} Element;
typedef struct
{
int NrOfItems;
struct Element *Head;
} PrQueue;
And that's the structure. All of these code parts are in different files. The first one is main.c , second one is functions.c and the third one is a .h header file. So what I need is somehow make it easier for the user to create the priority queue in main, I should somehow get rid of the pointers symbol in main. I don't really know how it should look, but as I understand it shouldn't use * in the main. Any ideas what and how I should change?
Thanks!
Upvotes: 0
Views: 75
Reputation: 73161
My recommendation is to convert your create()
function to an init()
function; this will allow the user to create PrQueue
objects inside other objects and/or on the stack, rather than only on the heap:
void init(PrQueue * Meta)
{
Meta->NrOfItems = 0;
Meta->Head = NULL;
}
It also means there is no possibility of the function failing, so the user won't have to do any error-checking.
The user could use it like this:
int main(int argc, char ** argv)
{
PrQueue q;
init(&q);
[...]
}
Upvotes: 1