如何获取指向动态分配对象的指针的基址

How to get the base address of a pointer to a dynamically allocated object

本文关键字:指针 对象 动态分配 何获 取指      更新时间:2023-10-16

我在上面定义了一个名为"Pieces"的结构main()

struct Pieces {
    char *word;
    int jump;
}

在我的main()中,我有:

int main() {
    Pieces *pieceptr;
    readFile(preceptor);
    cout << (*pieceptr).word << endl; //SEGFAULT occurs here
    return 0;
}

readFile()中,我有:

void readFile(Pieces *&pieceptr) {
    ifstream fin;
    fin.open("data");
    int pieceCount;
    if(fin.is_open()) {
        fin >> pieceCount;
        pieceptr = new Pieces[pieceCount];
        for (int i = 0; i < pieceCount; i++) {
            char *tempWord = new char[20];
            fin >> tempWord >> (*pieceptr).jump;
            (*pieceptr).word = new char[stringLength(tempWord)];
            stringCopy((*pieceptr).word, tempWord);
            delete []tempWord; 
            tempWord = NULL;
            pieceptr++;
        }
    } else {
        cout << "Error opening file." << endl;
    }
    fin.close();
}

此项目的约束条件包括:

  • 创建我自己的字符串函数
  • 方括号只应在动态声明或解除分配数组时使用。
  • 不要使用指针算法,除了 ++ 和 -- 或设置回到主页指针。
  • 不要在指针中使用箭头 (->( 表示法。

我已经广泛测试了 readFile() 函数,它按照我想要的方式运行(它正确填充了 Pieces 数组(,但是在我调用 readFile() main()后,我需要再次访问数组的第一个元素。就像现在的代码一样,由于指针已超出数组的范围,我得到了一个段错误。如何在不使用指针算法的情况下重置指针以指向数组中的第一个元素?

多个指针可以指向同一内存点。指针也可以复制。解决您的问题的最简单方法是创建另一个指针并在其上执行所有增加操作。

void readFile(Pieces *&pieceptr) {
    ifstream fin;
    fin.open("data");
    int pieceCount;
    if(fin.is_open()) {
        fin >> pieceCount;
        pieceptr = new Pieces[pieceCount];
        Pieces* pieceIterator = pieceptr;
        for (int i = 0; i < pieceCount; i++) {
            char *tempWord = new char[20];
            fin >> tempWord >> (*pieceIterator).jump;
            (*pieceIterator).word = new char[stringLength(tempWord)];
            stringCopy((*pieceIterator).word, tempWord);
            delete []tempWord; 
            tempWord = NULL;
            pieceIterator++;
        }
    } else {
        cout << "Error opening file." << endl;
    }
    fin.close();
}