gpt4 book ai didi

c - 为什么二维数组用于堆栈?为什么不能将一维数组用于堆栈?

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:18 26 4
gpt4 key购买 nike

此处,s[20][20] 在函数 pre_post 中声明。但是 push 操作涉及将字符串压入堆栈。这是怎么做到的?为什么我们不能用 s 的一维数组执行程序,比如堆栈的 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;
}

最佳答案

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

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.

关于c - 为什么二维数组用于堆栈?为什么不能将一维数组用于堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32697809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com