c - Why a 2D array is used for stack? Why cant a 1D array be used for a stack? -
here, s[20][20]
declared in function pre_post
. push
operation involves pushing string stack s. how done? why cant execute program 1d array s s[20]
stack??
#include<stdio.h> #include<string.h> #include<ctype.h> void push(char item[],int *top,char s[][20]) //pushes symbol item onto stack s { *top=*top+1; //top incremented strcpy(s[*top],item); //item written onto stack } char *pop(int *top,char s[][20]) //pops out topmost element of stack s { char *item; item=s[*top]; *top=*top-1; return item; } void pre_post(char prefix[],char postfix[]) //function convert prefix 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 expression in reverse manner { symbol=prefix[i]; //the last symbol scanned first ch[0]=symbol; ch[1]='\0'; switch (symbol) //checks whether symbol 1 among fiveoperators given.(next line) //if yes execute corresponding statements { case '+': case '-': case '*': case '/': case '^': op1=pop(&top,s); //the topmost operand of stack s popped , stored op1 op2=pop(&top,s); //the next operand of stack s popped , stored op2 strcpy(postfix,op1); //copies op1 postfix strcat(postfix,op2); //concatenates op2 postfix strcat(postfix,ch); //concatenates ch postfix push(postfix,&top,s); //pushes postfix onto stack s break; default: if(isalnum(symbol)) //it means switch case not satisfied i.e. symbol operand push(ch,&top,s); //pushes operand onto stack s } } } int main() { char prefix[20]; char postfix[20]; printf("\n\n enter prefix expression \n\n"); gets(prefix); pre_post(prefix,postfix); printf("\n\n postfix expression %s \n\n",postfix); return 0; }
you need 1-d array of characters represent string.
char str[20]; // array of characters can hold string // of 19 characters.
then, need 2-d array of characters represent array of strings.
char str[100][20]; // array 100 strings. each element of array // can hold string of 19 characters.
Comments
Post a Comment