背景:剛學完棧,實現棧的應用—表示式求值。
栗子:中綴:(20 + 5 + 1*3)/ 14
字尾: 20 5 + 1 3 * + 14 /
出現的問題:
強制轉換出現問題 將指向其他型別資料的指標賦值給void型別指標的時候,該記憶體中存放資料仍是最開始的資料型別。
對運算元進行計算後,會覆蓋原來的結果。例如先將20+5的結果25入棧,後將1*3的結果3壓入棧,會覆蓋之前的25。
解決方法:
如果強制將string *型別通過(int *)進行轉換則會出錯,使用stoi()函式;反之,使用to_string()函式。
兩次使用的變數(就是乙個變數)共用同一段記憶體(該變數為區域性變數,生存期內未釋放空間),動態申請空間即可。
#include #include #include #include #include using namespace std;
typedef struct stacknode snode;
class linkstack ;
linkstack::linkstack()
linkstack::~linkstack()
void linkstack::push(void* x)
int linkstack::pop()
void * linkstack::gettop()
int cal(void* b, void* a,string s)
void* res(linkstack *s, vectora)
else
cout << "s:";
for (snode *p = s->top; p != null; p = p->next)
cout << "null"}int main();
cout << "res is " << *(string *)res(s, a) << endl;
delete s;
system("pause");
}
表示式求值
程式的說明見清華大學出版社 資料結構 c語言版 include include define stack init size 40 define stackincrement 20 define ok 1 define false 0 typedef structs stack typedef st...
表示式求值
既然是表示式求值,自然需要在記憶體中儲存計算結果以及中間值。在 用c語言寫直譯器 一 中提過 變數要求是若型別,而 c 語言中的 view plaincopy to clipboardprint?in basic io.h define memery size 26 typedef enum var...
表示式求值
寫了乙個下午,各種糾結,各種問,終於搞明白了。但是自己還是想出來的一點東西的。很爽歪歪的,哈哈。先貼第一次的 include include include include include includeusing namespace std char data 7 7 int sign char ...