/* preval.c, class example 1 March 2012 Lin Jensen see assembly program preval.a There is a problem in C, that when a pointer is passed to a function, a COPY of the address is passed, if this copy is incremented, that doesn't affect the original. The solution will be to store a "working pointer" in memory, pass the address of this pointer, which is now of type char** (a pointer to the pointer to the (current) start of the string. Algorithm: preval() if numeric character return binary value of it if '+' return preval() + preval() if '*' return preval() * preval() else try again (ignore space, for example) */ #include /*-----------------------------------------------------------------------------*/ int preval(char ** place) { char* e = *place; // e points to the next char to be considered char ch; while (ch = *e++) // get next character, and "consume" { // this is a loop, to detect end of string, and skip blanks *place = e; // update the stored pointer if ('0' <= ch && ch <= '9') return ch & 0xF; // binary value of digit if (ch =='+') return preval(place) + preval(place); // add -- note *place will be changed if (ch =='*') return preval(place) * preval(place); // multiply // now, you can implement subtract, divide } return -999; // EOS too soon } /*-----------------------------------------------------------------------------*/ int main() { puts("Enter prefix arith expression, single digits and + * allowed"); char expression[100]; while (*(gets(expression))) { // get an expression, until empty line (first char is '\0') char *head = expression; // start of string stored int result = preval (&head); // pass ADDRESS of this pointer printf("value= %d\n>",result); } return 0; }