Originally Posted by
gajya
@Salem I think I have done
Code:
#include<stdio.h>
#include<stdlib.h>
struct Queue {
int data[10];
int front;
int back;
};
void queueInit(struct Queue *q) // Initialise
{
(*q).data[0] = 0;
(*q).front = 0;
(*q).back = 0;
}
void queueEnqueue(struct Queue *q, int data) // enqueue a value
{
(*q).data[0] = data; // add 1 into queue
(*q).front = 0;
(*q).back = 0;
}
int main()
{
struct Queue q;
queueInit(&q);
queueEnqueue(&q, 1); // enqueue a value
return 0;
}
Now I need help in enqueue
Okay, but ...
First, let's talk about notation:
Code:
(*q).data[0] = data;
q->data[0] = data;
Those two lines ^^ mean exactly the same thing.
In C, the -> operator was created specifically to create a shorthand for (*pointer).member expressions. In much the same way that the ++ and -- operators were created as a shorthand for x = x + 1. They're the same under the hood.
So, first of all, you wrote a completely valid expression, and that statement is totally correct.
But, second of all, the "idiomatic" way to write that is to use the -> operator, and every C programmer (including me) is going to read that, wince, and go "okay, but ..."
Next, let's talk about "meanings." You have a queue of your own data type. How do you know when the queue is empty? How do you know when the queue is not empty? How do you know how many values are in the queue? Also, how do you handle an error? If the queue has 10 values in it and I call enqueue, what will happen? If the queue has no values in it and I call dequeue, what will happen?
(This is not a trick question: these are normal conditions that can be expected to occur. The designer of the library, which in this case is YOU has to make the rules for this. So... what are the rules?)
Now here are some more questions. Given this code:
Code:
typedef struct Queue Queue;
extern bool q_is_empty(Queue *);
extern size_t q_length(Queue *);
extern error_t q_enqueue(Queue *, value_t data);
struct Queue * q = &(struct Queue){ .data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, .front=0, .back=0 };
printf("%s\n", q_is_empty(q) ? "empy" : "not empty"); // what does this print?
printf("%d\n", q_length(q)); // what does this print?
printf("%d\n", q_enqueue(q, (value_t){0})); // what does this print?
// what does the q structure look like after that last call to enqueue?
What do the statements print, and what are the new values in the queue structure? (This is all about you making decisions, and understanding how these things are going to be used.)
[/code]