Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ol> <li><p>One serious problem here is</p> <pre><code>char cont[] = { 'y' }; ... s("%s", &amp;cont[0]); </code></pre> <p>You've only reserved <strong>one</strong> byte but <code>scanf</code> will write at least 2 bytes, meaning that you are going to have a buffer overflow and then the overall behaviour is unpredictable. If you want to read a single character then use<code>"%c"</code> as a pattern but the problem here is that characters will be in the buffer for the next read, so you are going to have to clear the buffer.</p> <p>It's much easier to do:</p> <pre><code>char line[1024]; fgets(line, sizeof line, stdin); if(line[strlen(line)-1] == '\n') line[strlen(line)-1] = 0; if(strcmp(line, "Y") == 0 || strcmp(line, "y")==0) </code></pre> <p>It's a little more code but it's safer this way.</p></li> <li><p>There are many queues, there are fifo, lifo, and depending on it you choose how to build it</p></li> <li><p>When dealing with queues, it's better to use function names like <code>push</code>, <code>pop</code> and <code>top</code> because they are widely used among other programmers and queue libraries. Use these names instead.</p></li> <li><p>In your case, instead if remembering with <code>front</code> and <code>rear</code> you should use <code>memmove</code> instead and use a variable <code>len</code> to count the current number of elements in the node. Once you've popped one element, you gained new space for more elements.</p></li> </ol> <p>Also, try to use fewer global variables and more encapsulation: (in my example I am not going to care about <code>malloc</code> returning <code>NULL</code>, I want to keep it short)</p> <pre><code>#include &lt;string.h&gt; /* for size_t */ typefed struct { size_z len; size_z max_size; int *data; } queue; void queue_init(queue *q, size_t max_size) { q-&gt;len = 0; q-&gt;max_size = max_size; q-&gt;data = malloc(max_size * sizeof *(q-&gt;data)); /* this is a good trick! * If you need to change the datatype of 'data', * you only need to change the definition of it. * This code is valid for any type */ } int push(queue *q, int data) { if(q-&gt;len == q-&gt;max_size) return 0; /* not enough space */ q-&gt;data[q-&gt;len++] = data; return 1; } int top(queue *q, int *data) { if(q-&gt;len == 0) return 0; /* no elements in the queue */ *data = q-&gt;data[0]; return 1; } int pop(queue *q, int *data) { if(top(q, data) == 0) return 0; memmove(q-&gt;data, q-&gt;data + sizeof *(q-&gt;data), q-&gt;len--); return 1; } </code></pre> <p>BTW:</p> <pre><code>#define p printf #define s scanf </code></pre> <p>Just like Daniel Fischer said, this is ugly; don't do that.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload