作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 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/
目前我有几个配置了以下目录的catalina bases, conf logs server webapps work bin、lib 和common 目录都还在$CATALINA_HOME 中。 我
我是一名优秀的程序员,十分优秀!