I am new to C. I hav开发者_StackOverflowe no idea about how to write a C function which creates an empty queue and return a void pointer.
void* queue_open(void)
I also want to know how to write a C function which puts an element at end of a queue.
void queue_put(void *p, void *elementp)
Thanks for your help!
If you are coming from an object oriented background (as your method signatures seem to indicate).
Object oriented idea -> good way to do it in C
Object creation -> malloc a struct, then pass it into an initialization function
struct queue* q = (struct queue*)malloc(sizeof(struct queue));
queue_initialize(q);
if you want, you can wrap this in a function, like so
struct queue* queue_construct() {
struct queue* q = (struct queue*)malloc(sizeof(struct queue));
queue_initialize(q);
return q;
}
Note that these pointer shouldn't point to void*, let C do at least some of the type checking for you.
Implement a method -> create a function that takes a struct pointer to the "almost this" struct.
struct user* user = ... whatever we do here ...;
queue_add(q, (void*)user);
As far as how to actually implement a queue, I suggest a good data structures or algorithms book, as there are many ways to go about it; and, the specific techniques you choose will have different impacts on performance and reliability. There's no one best way, it depends heavily on how the queue is to be used, and which aspects of performance are more important.
The book I recommend is Introduction to Algorithms. This book is overkill for most situations, with very detailed listings of nearly every major data structure you are likely to encounter in the first few years of programming. As such, it makes a great reference, despite its attempt at a language neutral approach, which now looks odd when compared to common programming languages.
Once you understand what is going on, you can do it in nearly any language.
You need to decide what a queue element should look like, what a queue is, and what it means for a queue to be empty. If you know those things, writing queue_open
and queue_put
should be pretty easy. I'd suggest that you start by defining a structure that represents your queue element.
You can learn about queues here:
http://en.wikipedia.org/wiki/Queue_(data_structure)
While you could easily copy and paste the sample code from the link above and with little modification solve your homework problem, you are not going to learn a lot by doing that.
After understanding a queue conceptually, I recommend you try to implement it yourself, then use the sample code from the link above as a reference when you get stuck.
The best thing you could do is pair up with another student in your class who is smarter than you. Then pair program ( http://en.wikipedia.org/wiki/Pair_programming ) with him/her to solve the problem. You'll become a better programmer.
精彩评论