Tom Kelliher, CS 220
Nov. 12, 1997
Read Chapter 8.
Consider the two-dimensional array:
int data[3][4];How much storage to allocate?
Conceptually:

How is it mapped onto the 1-D memory?

data[i][j]:
&data[i][j] = data
+ i * (# of columns) * (sizeof(data element))
+ j * (sizeof(data element))
# of columns = length of row.

data[i][j]?
Operations:
Array implementation:
const int stackSize = 128;
int stack[stackSize];
int *stackPointer = stack + stackSize; // NOTE: this is one element
// beyond the end of stack.
/**********************************************************************
* isEmpty() --- returns 1 if the stack is empty.
**********************************************************************/
int isEmpty(void)
{
return stackPointer == stack + stackSize;
}
/**********************************************************************
* isFull() --- returns 1 if the stack is full.
**********************************************************************/
int isFull(void)
{
return stackPointer == stack;
}
/**********************************************************************
* push() --- push item onto the stack.
**********************************************************************/
void push(int item)
{
if (isFull())
die("Trying to push onto a full stack");
*--stackPointer = item;
}
/**********************************************************************
* pop() --- pop and return the top of stack item.
**********************************************************************/
int pop(void)
{
if (isEmpty())
die("Trying to pop from an empty stack.");
return *stackPointer++;
}
Consider evaluating these postfix expressions:
23 17 + 18 + 2 5 + 4 2 + * 1 7 4 * + 5 + 2 3 + 4 5 + * 2 3 4 * + 5 + 1 2 + 3 + 4 + 5 + 1 2 3 4 5 + + + +
An algorithm to evaluate a single postfix expression:
while not end of line
token = next token from input stream
if token is a number
push(token);
else if token is an operator
operand2 = pop();
operand1 = pop();
result = the value of the operator in token applied to
operand1 and operand2;
push(result);
else // invalid token
terminate
end_if
end_while
answer = pop();
print answer;
Any errors to check?
See postfix.cc on the class home page. To compile and run:
bluebird:~/Class/Cs220/Handouts % g++ -o postfix postfix.cc bluebird:~/Class/Cs220/Handouts % ./postfix Hit me with some postfix expressions. Type the EOF character to quit. ? 23 17 + 18 + 58 ? 2 5 + 4 2 + * 42 ? 1 7 4 * + 5 + 34 ? ^D bluebird:~/Class/Cs220/Handouts %You'll use postfix.cc as the model from which you write your MAL program. I.e., functions and parameters.