如何获取指向动态分配对象的指针的基址
How to get the base address of a pointer to a dynamically allocated object
我在上面定义了一个名为"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();
}
相关文章:
- 为什么指针对象没有调用默认构造函数
- 如何访问双指针对象中的方法
- 如何使用智能指针对象执行成员函数指针
- 调用带有指针对象错误的指针变量
- 如何从模板类重载创建的指针对象上的运算符?
- C++指针对象的运算符重载
- 如何初始化数组指针对象
- 如何打印出唯一指针对象向量中的值(基于范围的循环)?C++
- C++指针对象差异
- 涉及继承,指针对象的交易以及何时进行的问题
- 表达式必须在C 中具有指针对象类型
- 下标需要数组或指针类型表达式必须具有指针对象类型
- 字符指针对象和相应的字符数组元素比较
- 如何在 c++ 中克隆为弱指针对象
- 指针对象使用CPP中的指针表达式进行比较
- Visual Studio中智能指针对象的自定义视图
- 使用指针 /对象 /模板参数正确构成
- 如果我确定只有一个线程一次处理指针/对象,则C/C 仍应使用同步
- 如何将值分配给指针对象 c++
- 更改智能指针对象,然后访问它