【发布时间】:2018-09-04 08:50:08
【问题描述】:
我对这个程序有一些疑问,这里我们创建整数到数组并在其中存储 char
考虑一下,如果我们将中缀写到 POSTFIX 程序中,那里将使用相同的堆栈操作函数
我们将括号和操作数存储在堆栈中,我想问一下stack->array中是否存储了ASCII值
为什么不需要类型转换
由于整数需要 4 个字节的内存,那么 1 字节 char 如何存储在该数组中,不仅存储而且我们如何使用该整数数组访问所有 char 变量,因为根据指针算术*(array+i)如果数组是指针,将提前 4 个字节为整数
#include <stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
// Stack type
struct Stack
{
int top;
unsigned capacity;
int* array;
};
// Stack Operations
struct Stack* createStack( unsigned capacity )
{
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
if (!stack) return NULL;
stack->top = -1;
stack->capacity = capacity;
stack->array = (int*) malloc(stack->capacity * sizeof(int));
if (!stack->array) return NULL;
return stack;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1 ;
}
char peek(struct Stack* stack)
{
return stack->array[stack->top];
}
char pop(struct Stack* stack)
{
if (!isEmpty(stack))
return stack->array[stack->top--] ;
return '$';
}
void push(struct Stack* stack, char op)
{
stack->array[++stack->top] = op;
}
// The main function that returns value of a given postfix expression
int evaluatePostfix(char* exp)
{
// Create a stack of capacity equal to expression size
struct Stack* stack = createStack(strlen(exp));
int i;
// See if stack was created successfully
if (!stack) return -1;
// Scan all characters one by one
for (i = 0; exp[i]; ++i)
{
// If the scanned character is an operand (number here),
// push it to the stack.
if (isdigit(exp[i]))
push(stack, exp[i] - '0');
// If the scanned character is an operator, pop two
// elements from stack apply the operator
else
{
int val1 = pop(stack);
int val2 = pop(stack);
switch (exp[i])
{
case '+': push(stack, val2 + val1); break;
case '-': push(stack, val2 - val1); break;
case '*': push(stack, val2 * val1); break;
case '/': push(stack, val2/val1); break;
}
}
}
return pop(stack);
}
// Driver program to test above functions
int main()
{
char exp[] = "231*+9-";
printf ("Value of %s is %d", exp, evaluatePostfix(exp));
return 0;
}
【问题讨论】:
-
请把
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));写成struct Stack *stack = malloc(sizeof *stack);,它更短更干。至于你的问题,C中的字符是小整数,这就是为什么在int变量中存储char值没有问题,它们都是整数,你可以确定任何char都适合int(关于签名有一些复杂性,但让我们忽略它)。 -
a
char只是一个数字,唯一的特殊之处在于它通常被解释为一个字符。sizeof(int) > sizeof(char),因此将char分配给int没有问题 -
分配时无需将 void* 投射到任何其他指针。只有在 C++ 中你需要这样做(但你不使用 malloc ofc ;))