[英]storing char in an array of integers
我对此程序有疑问,在这里我们要创建整数数组并在其中存储char
考虑一下,当我们将后缀写入后缀程序时,将使用相同的堆栈操作功能
然后将括号和操作数存储在堆栈中,我想问一下是否将ASCII值存储在stack->array
,为什么不需要类型转换,并且由于整数需要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;
}
char
是机器中可包含基本字符集的最小可寻址单元。 它是一个整数类型 。 实际类型可以是带符号的也可以是无符号的。 它包含CHAR_BIT位。
它的大小几乎总是小于int的大小。 因此,可以将char
轻松存储在int
。
我们如何使用该整数数组访问所有char变量,因为如果数组是指向整数的指针,则根据指针算术*(array + i)将提前4个字节
这是可能的,因为在将char
存储到int
,将以int大小的间隔存储它们。 由于top
是一个int
,因此其上的指针算法(++)将其地址值增加一个int
的大小。
stack->array[++stack->top] = op;
这就是在您同时检索char
时发生的情况。 top
的指针运算top
(-)将其地址值减小一个int
的大小。
return stack->array[stack->top--] ;
因此它可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.