c - Push and Pop function -


im trying replicate push , pop functions using integers , int array. im having trouble finding size of array in push function. how find size or 'push' new value array

typedef int data_t; int main(int argc, char **argv){ int *s, i;      s = malloc(10*sizeof(int));     s = null;     push(1,s);     push(3,s);      for(i = 0; s[i]; i++){         printf("%d\n",s[i]);         }     return 0; }  void push(data_t n,int *s ){     int size = 0, = 0;      if (s == null){         s[0] = n;     }     else{         while(s[i] != null){             size++;             i++;         }         s[size] = n;     } } 

firstly, glad see didn't cast result of malloc.

  1. your

    int   main(int argc, char **argv){ 

    be assured doesn't have side effect on code behaviour, have seen of people doing way, improves readability. should be,

    int main(int argc, char **argv){   
  2. this

    s = malloc(10*sizeof(int)); s = null; 

    should

    s = null;         s = malloc(10*sizeof(int)); 
  3. i don't comprehend trying through this:

    for(i = 0; s[i]; i++) 

    may should like,

    for(i = 0; < max_length; i++)  //max_length should integer #defined somewhere in code 

apart these obvious mistakes, can think adding check ensure that, in while loop in function push() don't overrun value of size s can accommodate.

then, instead of doing

if (s == null){     s[0] = n; } 

in push(), have preferred checking if memory allocated after malloc. so,

s = malloc(10*sizeof(int)); if (s == null) {     //error handling supposed done if no memory allocated } 

this should looking forward to:

#include <stdio.h> #include <stdlib.h>  typedef int data_t;  int top;      void push(data_t,int*); int  pop(int*);  int main(int argc, char **argv) {     int *s = null, i;     top = -1;      s = malloc(10*sizeof(int));     if(s == null)     {         printf("memory allocation failed");         //other error handling implementation if     }     push(1,s);     push(2,s);     push(3,s);      for(i = 0; <= top; i++){         printf("%d\n",s[i]);     }      printf("\n popping:\n");     pop(s);      for(i = 0; <= top; i++){         printf("%d\n",s[i]);     }      return 0; }  void push(data_t n,int *s ) {     //check if stack full     if (top == 10)     {         printf("stack full");         //other implementation     }     else     {        ++top;        s[top] = n;     } }  int pop(int *s) {     //check if stack empty     if (top == -1)     {         printf("stack empty");         //other implementation     }     else     {        return s[top--];     } } 

the code untested travelling.


Comments