[C ++深度复制const char *是否在类数组中?

问题描述 投票:1回答:1

所以我在上课时遇到问题。在这个类中,我应该拥有一些数据数组。我在分配和创建新数据方面没有问题,例如x2.NewAccount(“ 123456”,1000);这很好,问题是当我试图用指向某个变量的字符串创建数据时。我对深度复制有所了解,但在我的案例中我不知道如何编程=运算符+我认为这是strcpy,但那也不能正常工作。

PS:这是一个学校程序,所以请不要因为没有使用标头和使用Im不在代码中使用的一堆插件而判断我。它是由我的学校制作的,我不允许更改它们+添加它们(我知道使用c ++的字符串会容易得多。)谢谢你的帮助。

#ifndef __PROGTEST__
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <cctype>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
#endif /* __PROGTEST__ */

struct data_history{
    int money = 0;
    bool Income;
    const char * UnStr;
    const char * to_from;
};

struct client{
    const char * accID;
    int Balance;
    int def_bal;
    data_history * history;
    int in_index = 0;
    int in_cap = 10;

    friend ostream &operator << (ostream &output , client p){
        output << p.accID << ":" << endl << "   " << p.def_bal << endl;
        for (int i = 0 ; i < p.in_index ; i++){
            if (p.history[i].Income == false)
                output << " - " << abs(p.history[i].money) << ", to: " << p.history[i].to_from << ", sign: " << p.history[i].UnStr << endl;
            else
                output << " + " <<abs(p.history[i].money) << ", from: " << p.history[i].to_from << ", sign: " << p.history[i].UnStr << endl;
        }
        output << " = " << p.Balance << endl;
        return output;
    }
};

class CBank
{
public:
    int cap = 10;
    int index = 0;
    client * database;
    ~CBank(){
        for (int i = 0 ; i < index ; i++)
                delete[] database[i].history;
        delete[]database;
    }
    CBank(){
        database = new client[cap];
    }
    bool NewAccount ( const char * accID, int initialBalance ){
        for(int i = 0 ; i < index ; i ++)
            if (accID == database[i].accID) {
                return false;
            }
        //strcpy (database[index].accID , accID );  // Im getting errors while compileing (cuz I was using const char * for database.accID when i chenged it i got program crash. 
        database[index].accID = accID;
        database[index].Balance = initialBalance;
        database[index].def_bal = initialBalance;
        database[index].in_cap = 10;
        database[index].history = new data_history[database[index].in_cap];
        index ++;
        return true;
    }
    client Account (const char * accID ){
        const char * input  =accID;
        for (int i = 0 ; i < index ; i++){
            if (database[i].accID == input )
                return database[i];
        }
        throw "error";
    }
    void print (){
        for (int i = 0 ; i  < index ; i ++) {
            cout << endl;
            cout << i << " = "<< " ID = " << database[i].accID << " | Balance = " << database[i].Balance << endl;
            cout << "===Account history ===\n\n";
            for (int y = 0 ; y < database[i].in_index; y++) {
                cout << "Was it for him? : " << boolalpha << database[i].history[y].Income
                    << "\nHow much : " << database[i].history[y].money << "\nUnique string : "
                    << database[i].history[y].UnStr << "\nfrom/to: " << database[i].history[y].to_from << endl << endl;
            }
        }
    }

private:

};


#ifndef __PROGTEST__
int main ( void )
{
    char accCpy[100], debCpy[100], credCpy[100], signCpy[100];
    CBank x2;
    strncpy ( accCpy, "123456", sizeof ( accCpy ) );
    assert ( x2 . NewAccount ( accCpy, 1000 ) );
    x2 . print();
    cout << "\n\n\n\n";
    strncpy ( accCpy, "987654", sizeof ( accCpy ) );
    assert ( x2 . NewAccount ( "987654", -500 ) );
    x2 . print();
}
#endif /* __PROGTEST__ */
c++ arrays string deep-copy
1个回答
0
投票

[使用database[index].accID = accID;时,您只是在进行浅表复制(并且依赖于调用者来保持此内存有效,因为可以访问指针)。

您已经正确地确定需要执行深层复制,但是client::accID只是一个指针,但是除非将其初始化为指向某些内存,否则您不能将其复制到其中。

执行此操作的一种方法是动态分配和管理client::accID,类似于您动态分配和管理client::history的方式。

代替strcpy (database[index].accID , accID );database[index].accID = accID;,请尝试:

size_t bufsize = strlen(accID) + 1;
char *buf = new char[bufsize];
memcpy(buf, accID, bufsize);
database[index].accID = buf;

并在析构函数中添加:

delete[] database[i].accID

正如其他人指出的那样,这种C ++编程风格非常容易出错,并且社区对此并不满意。使用标准库类可以轻松避免这种手动内存管理。即使进行了上述更改,但是如果您开始复制CBank对象,您的程序也会遇到未定义的行为。

即使您不必执行任务,也应考虑使用以下方法将其重写为练习:

  • [std::string而不是accID;的C字符串
  • [std::vector而不是data_history数组

也供您参考:

if (database[i].accID == input )

不会对C弦做任何期望...

© www.soinside.com 2019 - 2024. All rights reserved.