c++ - 在 C++ 中打印一个 char*

标签 c++ printing pointers char

我正在编写一个简单的程序。它只有一个类。有一个私有(private)成员 'char * number' 和两个函数(还会有更多,但首先这些应该可以正常工作 :))。

第一个应该将“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() 时,由于程序不再访问 *number 最初指向的内存,它会崩溃(即段错误)。要解决此问题,请改为执行以下操作:

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 变量,因为您不必自己处理内存管理开销,而且复制字符串也会更容易。

关于c++ - 在 C++ 中打印一个 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1054447/

相关文章:

c - 访问函数指针数组

c - 在 C 中释放 NULL 指针是一种好习惯吗?

c++ - 不变问题和隐式 move 构造函数

在 r 中使用 print 时删除前导括号

java - 如何在 JAVA 中将 2d 字符数组打印到 5x5 游戏板中并初始化以存储 "O' s"

css - 使用 css 从页脚隐藏 URL

c++ - 将 const T (&ref)[N] 绑定(bind)到 T[N] 类型的对象

c++ - 带有指针和比较器C++的优先级队列

c++ - 如何打印嵌套的 map - map - vector

c++ - 枚举值的行为是否像全局变量?