繁体   English   中英

用C ++打印char *

[英]Printing a char* in C++

我正在写一个简单的程序。 里面只有一节课。 有一个私人成员'char *号码'和两个功能(会有更多,但首先这些应该正常工作:))。

第一个应该将'source'复制到'number'变量中(我想这里的某个地方就是问题):

LongNumber::LongNumber(const char * source ){
        int digits = strlen(source);

        char* number = new char[digits+1];
        strcpy( number, source );
        //  cout<<number<<endl; - if the line is uncommented,
        //  the output is correct and there isn't a problem

}

和打印功能:

void LongNumber::print(){
    cout<<number<<endl;
    // when I try to print with the same line of code here..it crashes
}

当然,我错过了什么......但是什么?

(因为这是我的第一篇文章......你认为标签是否已经更正......你会如何标记帖子?)

先感谢您 :)

当您退出构造函数时,您的number char *数组将超出范围。 当你到达print()时,由于程序不再能够访问*数字最初指向的内存,它会崩溃(即分段错误)。 要解决此问题,请执行以下操作:

class LongNumber
{
     char *number;
     LongNumber(const char *source);
     ~LongNumber();
     void print();
};

LongNumber::LongNumber(const char * source ){
        int digits = strlen(source);

        number = new char[digits+1];
        strcpy( number, source );    
}

void LongNumber::print(){
    cout<<number<<endl;
}

不要忘记执行以下操作:

LongNumber::~LongNumber()
{
    delete [] number;    // to avoid memory leaks
}

我还强烈建议使用STL :: string而不是使用char *作为你的* number变量,因为你不必自己处理内存管理开销,复制字符串也会更容易。

LongNumber构造函数中,您声明一个名为number的新局部变量,并使用新的char数组对其进行初始化:

char* number = new char[digits+1];

相反,你应该省略char* ,这样它看起来不像一个新的变量声明并使用对象成员变量:

number = new char[digits+1];

使用当前代码,成员变量number永远不会被初始化,稍后在print使用它会导致错误。

你的问题在你的构造函数中:

LongNumber::LongNumber(const char * source )
{
  ...
  // you are declaring a new local variable called `number` here
  char* number = new char[digits+1];
  strcpy( number, source );
  ...
}

您没有复制到名为number的类成员变量,您在构造函数的主体中声明一个新的局部变量并使用它。 类成员变量未使用,可能未定义。 对于指针成员,这意味着该值可以是任何无效值 - 然后当您调用print时:

void LongNumber::print()
{
  cout<<number<<endl;
  // when I try to print with the same line of code here..it crashes
}

你在这里使用的number是类成员变量,正如我们所说的那样是未定义的。 然后对cout的调用将崩溃,因为它试图使用该无效指针。

修复是使构造函数使用正确的类成员变量:

LongNumber::LongNumber(const char * source )
{
  ...
  // use the class member variable `number` here
  number = new char[digits+1];
  strcpy( number, source );
  ...
}

它在我看来像你的声明数字作为局部变量。 如果你想在另一个函数中再次调用它,你必须在类定义中声明它...就像这样:

class LongNumber{
public:
        int digits;
        char* number;
        LongNumber(const char * source );
        void print();
}

LongNumber::LongNumber(const char * source ){
        digits = strlen(source);
        number = new char[digits+1];
        strcpy( number, source );
        //  cout<<number<<endl; - if the line is uncommented,
        //  the output is correct and there isn't a problem
}

void LongNumber::print(){
    cout<<number<<endl;
    // when I try to print with the same line of code here..it crashes
}

希望有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM