C++;堆栈程序Wsing指针数组发出新字符[len],其中len为2创建一个字符16? 我写了一个课程,我对C++的方法不太熟悉。我已经研究了字符数组,但无法找出问题所在。在分配空间时,空终止符似乎没有分配到所需的位置

C++;堆栈程序Wsing指针数组发出新字符[len],其中len为2创建一个字符16? 我写了一个课程,我对C++的方法不太熟悉。我已经研究了字符数组,但无法找出问题所在。在分配空间时,空终止符似乎没有分配到所需的位置,c++,pointers,stack,copy-constructor,character-arrays,C++,Pointers,Stack,Copy Constructor,Character Arrays,我的问题是这个。我正在分配一个数组,请参见下文: char* St =""; if(P.GetSize() > 0) { int StLen = P.GetSize() + 1; St= new char[StLen]; int i; for( i = 0;!P.isEmpty() && i < (int)strlen(St); i++)//StLen { *(St+i)= P.getTop();

我的问题是这个。我正在分配一个数组,请参见下文:

char* St ="";

if(P.GetSize() > 0)
{
    int StLen = P.GetSize() + 1;
    St= new char[StLen];

    int i;
    for( i = 0;!P.isEmpty() && i < (int)strlen(St); i++)//StLen
    {
        *(St+i)= P.getTop();

        P.Pop();
    }
    *(St+i) = 0;
    std::reverse( St, &St[ strlen( St ) ] ); //flip string to display bottom to top
}
char*St=”“;
如果(P.GetSize()>0)
{
int StLen=P.GetSize()+1;
St=新字符[StLen];
int i;
对于(i=0;!P.isEmpty()&&i<(int)strlen(St);i++)//StLen
{
*(St+i)=P.getTop();
P.Pop();
}
*(St+i)=0;
std::reverse(St,&St[strlen(St)];//翻转字符串以从下到上显示
}
如果p.GetSize()为1,并且我为空终止符添加了一个,那么行(int)strlen(St)仍然返回16作为读取数组的原始长度。我在下面发布了我的工作计划,供其他有同样问题的人参考

下面是我的工作解决方案 头文件:

 //Created By : Timothy Newport
//Created on : 4/26/2012
//===========================================
// NewportStack.h
//============================================
#pragma once

#include <iostream>
#include <iomanip>
#include <fstream>
#include <crtdbg.h>
#include <stack>
#include <string>
using namespace std;

const int MAX_POSTFIX = 30;
void infixToPostfix(const char *infix, char* postfix,ostream& os);
void WriteHeader(ostream& os);
void WriteResults(ostream& os,const char *postfix);

template<class T>
struct Node
{
    T data;
    Node<T> *prev;
};

template<class T>
class NewportStack
{
    private:        
        Node<T> *top; 
        int size;
    public:
        NewportStack();
        NewportStack(const NewportStack <T> & displayStack);
        ~NewportStack();
        void Push(T ch);
        void Pop();
        T getTop() const;
        bool isEmpty() const;
        const int GetSize() const;
        int SetSize(const int prvSize);
        bool checkPresidence(T data,char infix);
        void printStack() const;

        virtual ostream& Output (ostream& os, const NewportStack & S,
                                    const char infix,const char *postfix
                                    ,const int size) const;
};

//------------
//Constructor
//------------
template<class T>
NewportStack<T>::NewportStack()
{
    top = NULL;
    size = 0;
}
template<class T>
void NewportStack<T>::printStack() const
{
    Node<T>* w;
    w = top;
    while( w != NULL )
    {
        cout << w->data;
        w = w->prev;
    }
}
//------------
//Copy Constructor
//------------
template<class T>
NewportStack<T>::NewportStack(const NewportStack<T> &Orig)
{
    if (Orig.top == NULL) // check whether original is empty
    {
        top = NULL;
    }
    else
    {
        Node<T>* newPrev=new Node<T> ;

        Node<T>* cur = Orig.top;
        newPrev->data = cur->data;
        top = newPrev;
// Now, loop through the rest of the stack
        cur = cur->prev;        
        while(cur != NULL )
        {
            newPrev->prev = new Node<T>;
            newPrev = newPrev->prev;            
            newPrev->data = cur->data;  
            cur = cur->prev;
        } // end for        
        newPrev->prev = 0;
        cur = 0;

    } // end else
    size = Orig.size;
} // end copy constructortor

//------------
//DeConstructor
//------------
template<class T>
NewportStack<T>::~NewportStack()
{
    Node <T>* w = top;

    while(top!=NULL)
    {
        delete w;
        top=top->prev;
    }
    size =0;
}
//------------
//getsize
//------------
template<class T>
const int NewportStack<T>::GetSize() const
{
    return size;
}
//------------
//SetSize
//------------
template<class T>
int NewportStack<T>::SetSize(const int prvSize)
{
    return size = prvSize;
}
//------------
//Push
//------------
template<class T>
void NewportStack<T>::Push(T d)
{
    Node <T>* w= new (std::nothrow) Node<T>;

    if ( !w ) 
    {
       cerr << "Error out of memory in Push\n";
       exit (1);
    }
    w->data =d;

    if( top == NULL )
    {
        w->prev = NULL;
    }
    else
    {   
        w->prev = top;
    }
    top = w;
    w = NULL;
    size++; 
}

//------------
//Pop
//------------
template<class T>
void NewportStack<T>::Pop()
{   
    if( top == NULL )
        return;
    Node<T>* w = top;
    top = top->prev;
    delete w;
    w = NULL;
    size--;
}
//------------
//getTop
//------------

template<class T>
T NewportStack<T>::getTop() const
{
    if (isEmpty ()) 
        exit(0);
    return top->data;
}

//------------
//isEmpty
//------------
template<class T>
bool NewportStack<T>::isEmpty() const
{
    if(top == NULL)
    {
        return true;
    }
    return false;
}

//------------
//checkPresidence
//------------
template<class T>
bool NewportStack<T>::checkPresidence(T data,char infix)
{
    switch(infix)
    {
        case '+': case '-':
            switch(data)
            {
                case '+': case '-': case '*': case '/': case '%':
                         return true;
                default: return false;
            }           
        case '*': case '/': case '%': 
            switch(data)
            {
                case '*': case '/': case '%':
                       return true;
                default: return false;
            } 
        default: return false;
    }
}

//------------
//OutPut
//------------
template<class T>
ostream& NewportStack<T>::Output(ostream& os, const NewportStack<T>& S,
                                    const char infix,const char *postfix
                                    ,const int size) const
{
    NewportStack<T> P ( S );//***INVOKED COPY CONSTRUCTOR*****

    char* St = new char[21];

    int i;
    if(P.GetSize() > 0)
    {
        int StLen = P.GetSize();

        for( i = 0;!P.isEmpty();i++)
        {
            *(St+i)= P.getTop();

            P.Pop();
        }
        *(St+i) = 0;
        std::reverse( St, &St[ strlen( St ) ] ); //flip string to display bottom to top
    }
    else
        *(St+0) = 0;

    os <<left<<setw(20) << infix ;

    for(i = 0;i < (int)strlen(St);i++)
    {
        os << St[i];        
    }
    os << right<< setw(21-i);

    for(i = 0;i <size;i++)
    {
        os << postfix[i];       
    }
    os << endl;

    if(St != NULL)
    {
        delete[] St;
    }

    return os;                                      
}
//创建人:Timothy Newport
//创建日期:2012年4月26日
//===========================================
//NewportStack.h
//============================================
#布拉格语一次
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
常量int MAX_后缀=30;
void infixToPostfix(常量字符*中缀,字符*后缀,ostream&os);
无效书面负责人(ostream&os);
无效写入结果(ostream&os,常量字符*后缀);
模板
结构体类型
{
T数据;
节点*prev;
};
模板
类NewportStack
{
私人:
节点*顶部;
整数大小;
公众:
NewportStack();
NewportStack(const NewportStack和displayStack);
~NewportStack();
空隙推力(tch);
void Pop();
T getTop()常数;
bool isEmpty()常量;
常量int GetSize()常量;
int SetSize(const int prvSize);
bool checkPresidence(T数据,字符中缀);
void printStack()常量;
虚拟ostream和输出(ostream和操作系统、const NewportStack和S、,
常量字符中缀,常量字符*后缀
,const int size)const;
};
//------------
//建造师
//------------
模板
NewportStack::NewportStack()
{
top=NULL;
尺寸=0;
}
模板
void NewportStack::printStack()常量
{
节点*w;
w=顶部;
while(w!=NULL)
{
cout数据;
w=w->prev;
}
}
//------------
//复制构造函数
//------------
模板
NewportStack::NewportStack(常量NewportStack&Orig)
{
if(Orig.top==NULL)//检查原件是否为空
{
top=NULL;
}
其他的
{
Node*newPrev=新节点;
节点*cur=Orig.top;
newPrev->data=cur->data;
top=newPrev;
//现在,循环遍历堆栈的其余部分
cur=cur->prev;
while(cur!=NULL)
{
newPrev->prev=新建节点;
newPrev=newPrev->prev;
newPrev->data=cur->data;
cur=cur->prev;
}//结束
newPrev->prev=0;
cur=0;
}//结束其他
尺寸=原始尺寸;
}//结束复制构造函数
//------------
//解构器
//------------
模板
NewportStack::~NewportStack()
{
节点*w=顶部;
while(top!=NULL)
{
删除w;
top=top->prev;
}
尺寸=0;
}
//------------
//getsize
//------------
模板
常量int NewportStack::GetSize()常量
{
返回大小;
}
//------------
//设置大小
//------------
模板
int NewportStack::SetSize(const int prvSize)
{
返回大小=prvSize;
}
//------------
//推
//------------
模板
void NewportStack::Push(td)
{
Node*w=新(std::nothrow)节点;
如果(!w)
{
cerr数据=d;
if(top==NULL)
{
w->prev=NULL;
}
其他的
{   
w->prev=顶部;
}
顶部=w;
w=零;
大小++;
}
//------------
//流行音乐
//------------
模板
void NewportStack::Pop()
{   
if(top==NULL)
返回;
节点*w=顶部;
top=top->prev;
删除w;
w=零;
大小--;
}
//------------
//盖托普
//------------
模板
T NewportStack::getTop()常量
{
if(isEmpty())
出口(0);
返回top->data;
}
//------------
//空空如也
//------------
模板
bool NewportStack::isEmpty()常量
{
if(top==NULL)
{
返回true;
}
返回false;
}
//------------
//检查主席
//------------
模板
bool NewportStack::checkPresidence(T数据,字符中缀)
{
交换机(中缀)
{
案例“+”:案例“-”:
交换机(数据)
{
案例“+”:案例“-”:案例“*”:案例“/”:案例“%”:
返回true;
默认:返回false;
}           
案例“*”:案例“/”:案例“%”:
交换机(数据)
{
案例“*”:案例“/”:案例“%”:
返回true;
默认:返回false;
} 
默认:返回false;
}
}
//------------
//输出
//------------
模板
ostream&NewportStack::输出(ostream&os、const-NewportStack&S、,
常量字符中缀,常量字符*后缀
,const int size)const
{
NewportStack P(S);//***调用了复制构造函数*****
char*St=新字符[21];
int i;
如果(P.GetSize()>0)
{
int StLen=P.GetSize();
对于(i=0;!P.isEmpty();i++)
{
*(St+i)=P.getTop();
P.Pop();
}
*(St+i)=0;
std::reverse(St,&St[strlen(St)];//翻转字符串以从下到上显示
}
其他的
*(St+0)=0;

os
new char[StLen];
不会初始化内存。您应该使用
std::string
而不是像这样手动处理字符数组

如果你是
//Created By : Timothy Newport
//Created on : 4/26/2012
//===========================================
// NewportStackTester.cpp
//============================================
#include "NewportStack.h"
//------------
//Main
//------------
int main()
{
    //////////////////////////////////////////
    ///  Tester Part Two Test The class ///
    //////////////////////////////////////////

    char arr[] = "a+b-c*d/e+(f/g/h-a-b)/(x-y)*(p-r)+d";
    //char arr[] = "a+b-c*d/e+(f/g)";

    int len = (int) strlen(arr);
    char *postfix = new char[len+1];

    ofstream outputFile;
    outputFile.open("PostFix.txt");

    outputFile << "Infix is : " << arr<<endl<<endl;
    WriteHeader(outputFile);

    _strupr( arr); ///**** convert the string to uppercase ****

    infixToPostfix(arr,postfix,outputFile); 

    outputFile.close();



    system("notepad.exe PostFix.txt");

    return 0;
}
//------------
//infixToPostfix
//------------
void infixToPostfix(const char *infix, char* postfix, ostream & os) 
{   
    NewportStack <char> P;
    int len=strlen(infix);
    len += 1;
//  cout << "infix in infixToPostfix: " << infix << endl; 
    int pi = 0;
    int i=0;
    char ch;

   while( i < len && *(infix+i) !='\0')
   {
       ch = *(infix+i);

      if(ch >='A' && ch <='Z' )
      {
            postfix[pi++]= ch;
      }
      else if(ch =='+' ||ch =='-'||ch =='*'||ch =='/'||ch =='%')
      {       
            while(!P.isEmpty() && P.getTop() != '(' 
                && P.checkPresidence(P.getTop(), ch ) )
            {               
                postfix[pi++]= P.getTop();
                postfix[pi] = 0;                
                P.Pop();
            }

            P.Push(ch);         
       }
      else if(infix[i] == '(')
      {
            P.Push(infix[i]);
      }
      else// if(infix[i]==')')
      {
        while(!P.isEmpty() && P.getTop() != '(')
        {
            postfix[pi++] = P.getTop();
            P.Pop();
        }
        P.Pop(); //****remove the '(' from the stack top.
      }

     P.Output(os, P, ch, postfix, pi); // display after each read

     i++;    
   }
   // end of infix empty stack
   while(!P.isEmpty() )
   {
        postfix[pi++]= P.getTop();
        P.Pop();
   }
   postfix[pi] = 0; //add null terminator at the end of the string.
   //cout << "postfix 104: " << postfix << endl;
 P.Output(os,P,*infix,postfix,pi);// display final line
 WriteResults(os,postfix);
}
//------------
//WriteHeader
//------------
void WriteHeader(ostream& os)
{
    os <<left<< setw(20)<< "Input Characters" << setw(20)<< "Stack Item" << setw(20)
                << "PostFix" <<endl <<setw(20)<< "----------------"<< setw(20) 
                << "----------" << setw(20)<< "-------" <<endl;
}
//------------
//WriteResults
//------------
void WriteResults(ostream& os,const char *postfix)
{
    os << endl<< "The Final postfix is: " << postfix <<endl;
}
memset(St, '\0', StLen);