为什么2D数组用于堆栈?为什么1D数组不能用于堆栈?

时间:2015-09-21 14:29:24

标签: c stack

此处,s[20][20]在函数pre_post中声明。但push操作涉及将字符串推入堆栈。怎么做的?为什么我们不能使用1D数组执行程序,如s[20]用于堆栈??

#include<stdio.h>
#include<string.h>
#include<ctype.h>
void push(char item[],int *top,char s[][20])    //Pushes the symbol item onto stack s
{
  *top=*top+1;                                  //Top is incremented
  strcpy(s[*top],item);                         //Item is actually written onto stack
}

char *pop(int *top,char s[][20])                //Pops out the topmost element of stack s
{
  char *item;
  item=s[*top];
  *top=*top-1;
  return item;
}

void pre_post(char prefix[],char postfix[])     //Function to convert prefix to postfix
{
  char s[20][20];
  int top,i;
  char symbol,ch[2];
  char *op1,*op2;

  top=-1;
  for(i=strlen(prefix)-1;i>=0;i--)              //Scans the expression in   reverse manner
  {
    symbol=prefix[i];                           //The last symbol is scanned first
    ch[0]=symbol;
    ch[1]='\0';
    switch (symbol)                             //Checks whether the symbol is one among fiveoperators given.(next line)
                                                //If yes then execute the corresponding statements
    {
      case '+':
      case '-':
      case '*':
      case '/':
      case '^':
        op1=pop(&top,s);                        //The topmost operand of stack s is popped and stored as op1
        op2=pop(&top,s);                        //The next operand of stack s is popped and stored as op2

        strcpy(postfix,op1);                    //Copies the op1 into postfix
        strcat(postfix,op2);                    //Concatenates the op2 with postfix
        strcat(postfix,ch);                     //Concatenates the ch with postfix
        push(postfix,&top,s);                   //Pushes the postfix onto stack s
        break;
      default:
        if(isalnum(symbol))                     //It means that switch case is not satisfied i.e. symbol is a operand
          push(ch,&top,s);                      //Pushes the operand onto the stack s 
    }
  }

}

int main()
{
  char prefix[20];
  char postfix[20];
  printf("\n\n Enter the prefix expression \n\n");
  gets(prefix);
  pre_post(prefix,postfix);
  printf("\n\n The postfix expression is %s \n\n",postfix);
  return 0;
}

1 个答案:

答案 0 :(得分:2)

您需要一维字符数组来表示字符串。

char str[20]; // An array of characters that can hold a string
              // of up to 19 characters.

然后,您需要一个二维字符数组来表示字符串数组。

char str[100][20]; // An array 100 strings. Each element of the array
                   // can hold a string of up to 19 characters.