动态分配指针数组时应指向什么?

时间:2019-01-14 06:17:53

标签: c++ pointers memory

有时候,代码完全崩溃了。我怀疑这种情况正在发生,因为我的指针数组可能指向内存中的某个随机位置。我相信要设置一个位置,以便所有指针元素都指向一个组合位置。

从字数少的文件中读取时,它的工作效果很好。但是,一旦我从一个巨大的文件中读取了文件,我的程序就会被大量垃圾破坏。谢谢!

#include <iostream>
#include <fstream>
using namespace std;

class orignialData {
    char* data;

public:

    void setData(char* s) { data = strdup(s);}
    char* getData() const {return data;}
};

class dataClass {
    orignialData** W_;
    unsigned int capacity_;   // max number of words Dictionary can hold
    unsigned int numberOfWordsInDictionary_;

public:

    dataClass(char* filename);

    void addData();
    void viewAll() const;
    void reSize();
};

void dataClass::reSize() {
    static int i = 0;
    W_[i] = new orignialData;

    if (i == 7) {
        cout << "Dictionary is now the size of: " << i << endl;
    }

    i++;
}

dataClass::dataClass(char* filename) {
    fstream file;
    char buff[30];
    capacity_ = 8;

    file.open(filename, ios::in);

    if(file.fail()) {
        cout << "There was an error oppennig the file....\n";
    }

    W_ = new orignialData*[capacity_];

    while (file >> buff) {
        static int i = 0;


        reSize();

        W_[i] -> setData(buff);
        i++;
    }



    file.close();
};

void dataClass::viewAll() const {

    cout << W_[0] -> getData() << endl;
    cout << W_[1] -> getData() << endl;
    cout << W_[2] -> getData() << endl;
    cout << W_[3] -> getData() << endl;
    cout << W_[4] -> getData() << endl;
    cout << W_[5] -> getData() << endl;
    cout << W_[6] -> getData() << endl;
    cout << W_[7] -> getData() << endl;



}


int main() {

    dataClass dic("simple");

    cout << "calling the view all funcion....\n";
    dic.viewAll();



    return 0;
}

1 个答案:

答案 0 :(得分:0)

您正在while循环中将i初始化为0,该数组将仅填充一个元素,其余元素仅具有内存地址。进入while循环之前,将i初始化为0,然后只在内部增加i。