For some reason the change in pointer location made from a function does not carry back. When I run this and input something like 1 + 2, I get stack underflow.
Code:#include <stdio.h> /* supports I/O system */ #include <stdlib.h> /* misc declarations */ #include <string.h> /* supports string functions */ #define COLS 80 void calculator( char exp[ ] ); void push( char ch, char *stack, char *bos ); char pop( char *stack, char *tos ); int gets_s( char *buf, int size ); /* fgets with stdin */ int main( void ) { char exp[ COLS ]; /* the expressions */ gets_s( exp, COLS ); calculator( exp ); return 0; } void calculator( char exp[ ] ) { static char *stack; /* pointer to some free stack memory */ static char *tos; /* top of stack */ static char *bos; /* bottom of stack */ stack = ( char * ) malloc( COLS * sizeof( char ) ); if ( !stack ) { printf( "Allocation Failure" ); exit( 1 ); } tos = stack; bos = stack + ( COLS - 1 ); printf( "before parse: %s\n", exp ); push( 'a', stack, bos ); pop( stack, tos ); } void push( char ch, char *stack, char *bos ) { if ( stack > bos ) { printf( "Stack Full\n" ); } else { *stack = ch; stack++; *stack = '\0'; //printf( "pushed: %s\n", stack - 1 ); } } char pop( char *stack, char *tos ) { stack--; if ( stack < tos ) { printf( "Stack Underflow\n" ); return NULL; } return ( *stack ); } int gets_s( char *buf, int size ) { int error; /* returns null on error */ int c; /* a single "character" */ char *ptr; /* pointer to first \n in string */ if ( fgets( buf, size, stdin ) != NULL ) { if ( ( ptr = strchr( buf, '\n' ) ) != NULL ) { *ptr = '\0'; error = 1; } else { while ( ( ( c = getchar( ) ) != '\n' ) && ( c != EOF ) ) { } error = NULL; } } else { error = NULL; } return ( error ); }



LinkBack URL
About LinkBacks


