c++ - 从文件读取时将数据保存到指针数组

标签 c++ pointers memory

我不明白为什么我的指针数组只保存了我正在读取的文件的最后一行。当我将字符串文字替换为 setData() 函数时,代码工作正常。 “mann”文件包含的所有内容都是按字母顺序排列的一堆单词。谢谢。

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

class orignialData {

char* data;

public:

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

class dataClass {
    orignialData** W_;

public:

    dataClass(char* filename);

    void addData();
    void viewAll();
};

dataClass::dataClass(char* filename) {


    fstream file;

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

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

    W_ = 0;
    W_ = new orignialData*[5];

    for (int i = 0; i < 5; i++)
        W_[i] = new orignialData;

    char buff[30];
    char* temp;

    while(file >> buff) {

        cout << buff << endl;

        static int i = 0;

        W_[i] -> setData(buff);

        i++;
    }

    file.close();

}

最佳答案

代替 data = s,编写 data = strdup(s) 来制作内容的拷贝。否则,你会一次又一次地给同一个指针赋值,你会一次又一次地覆盖这个指针指向的内存中的内容。最后,您的临时缓冲区将包含文件的最后一行,并且所有指针都将指向该缓冲区。这就是您正在观察的...

关于c++ - 从文件读取时将数据保存到指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54173864/

相关文章:

c++ - 如何使用 'using' 声明模板基类的模板方法?

linux - Linux下通过内存限制进程

c - (void*) 在类型转换中意味着什么?

c - 带有 * 的 typedef 结构到 c 中的名称

c - 在C语言中,带有两个星号(**)的变量声明是什么意思?

c - C程序需要多少内存

memory - JBoss作为Windows服务。在哪里可以设置JAVA_OPTS?

c++ - 访问结构时出现段错误

c++ - 构造函数中的部分模板推导

c++ - 模数为哈希表中的地址创建错误的 int?