Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamically growing Stack in C
    primarykey
    data
    text
    <p>I'm experiencing some trouble with an assignment. I am supposed to implement a dynamically growing stack that doubles its size when it's full and halves it when it's 1/4 full. Since I am a total C beginner and are unfamiliar with pointers, I've looked through some examples and this is the Code I came up with.</p> <p>It actually compiles in gcc without warnings, but produces a "Segmentation fault" when I try to run it. I found out that this probably has to do with broken pointers, but I don't see any mistakes and would be glad if someone could point it out for me.</p> <p>Cheers</p> <pre><code># ifndef STACK_H # define STACK_H # include "stdlib.h" typedef struct stack { int *stack; int used; int size; } stack; stack* stck_construct() { stack *stck; stck-&gt;stack = (int *)malloc(10 * sizeof(int)); stck-&gt;used = 0; stck-&gt;size = 10; return stck; } void stck_destruct(stack *stck) { stck-&gt;stack = 0; stck-&gt;used = stck-&gt;size = 0; free(stck); } int stck_push(stack *stck, int val) { if (stck-&gt;used == stck-&gt;size) { stck-&gt;size *= 2; stck-&gt;stack = (int *)realloc(stck-&gt;stack, stck-&gt;size * sizeof(int)); } stck-&gt;stack[stck-&gt;used] = val; stck-&gt;used++; return 1; } int stck_pop(stack *stck, int *val) { *val = stck-&gt;stack[stck-&gt;used]; free(stck-&gt;stack); stck-&gt;used--; if (stck-&gt;used &lt;= (stck-&gt;size)/4) { if (stck-&gt;size &lt;=40) stck-&gt;size = 10; else stck-&gt;size /= 2; stck-&gt;stack = (int *)realloc(stck-&gt;stack, stck-&gt;size * sizeof(int)); } return 1; } int main(){ stack* test; test=stck_construct(); int i; int out; for (i =1; i&lt;=10; i++) stck_push(test, i); for (i =1; i&lt;=10; i++) { stck_pop(test,&amp;out); printf("%i\n", out); } stck_destruct(test); return 0; } # endif </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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