c - Initializing the stack with up to 10 values -
i'm trying make sure if initialization stack function gets values enter user, right codes print out different values original values enter. use %d. also, i'm working on different functions work stack such pop, push, goes top of stack, etc. work in while loop? however, here initialization stack function
typedef struct stack { int* darr; int size; int top; }stack; stack * initstack(int elements) { stack *s; s = (stack *)malloc(sizeof(stack)); s->darr = (int *)malloc(sizeof(int)*elements); s->size = 0; s->top = elements; return s; }
in main ()
int main() { stack s; int i; printf("hello user, please enter 10 different values build stack: \n"); for(i = 0; < 10; i++) { scanf("%d", initstack(i)); } printf("\nyou entered: \n%d\n\n", initstack(i)); return 0; }
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct stack { int* darr; int size; int top; }stack; stack *initstack(int elements){ stack *s; s = (stack *)malloc(sizeof(stack)); s->darr = (int *)malloc(sizeof(int)*elements); s->size = 0; s->top = elements; return s; } void dropstack(stack *s){ free(s->darr); free(s); } void push(stack *s, int v){ if(s->top == 0){ fprintf(stderr, "stack full!\n"); return ; } s->darr[--s->top] = v; ++s->size; } bool isempty(stack *s){ return s->size == 0; } int pop(stack *s){//need check isempty before pop --s->size; return s->darr[s->top++]; } int main(void) { stack *s = initstack(10); int i; printf("hello user, please enter 10 different values build stack: \n"); for(i = 0; < 10; i++){ int value; scanf("%d", &value); push(s, value); } while(!isempty(s)) printf("\nyou entered: \n%d\n", pop(s)); dropstack(s); return 0; }
Comments
Post a Comment