gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:44:34 25 4
gpt4 key购买 nike

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

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();
}

关于c++ - 如何获取指向动态分配对象的指针的基地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35387170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com