从文件写入字符串数组指针时出错(读取访问冲突)? CPP
Error when writing from file into pointer of string array (read access violation)? CPP
对于一个问题,我必须使用动态分配和函数(仅使用指针变量)从 .txt 文件中读取名称并按词汇顺序对名称进行排序。但是,我什至无法让读取功能正常工作。这是它写的:
void readNames(std::string* a[])
{
std::ifstream fin;
fin.open("names.txt");
for (int i = 0; i < 7; ++i)
{
fin >> *(a[i]);
std::cout << *a[i];
}
}
这是我在 main 中的调用方式:
std::string* names;
names = new std::string[7];
readNames(&names);
但是,当我 运行 这样做时,我得到了错误:
抛出异常:读取访问冲突。
这是 0xCCCCCCCC。
并显示了这个功能(不确定是否有帮助):
void _Check_offset(const size_type _Off) const { // checks whether _Off is in the bounds of [0, size()]
if (_Mysize < _Off) {
_Xran();
}
}
如果有人能帮我解决这个问题,我将不胜感激,谢谢!
为了详细说明 WhozCraig 的评论,我们假设如下:
names
驻留在栈上,所以我们给它地址 0x7f001000.
- 你分配的字符串数组驻留在堆上,所以我们给它地址0x1000
- 您将该地址分配给
names
,因此地址 0x7f001000 包含值 0x1000。
里面readNames
,a
是names
的地址,所以表达式*(a[i])
可以改写为:
*(*(&names + i))
对于 i=0,这是可行的。您基本上取消引用 a
一次以获取数组的开头,然后再次获取对第一个分配的 std::string
.
的引用
对于任何其他 i,您访问堆栈上的数据 (0x7f001000 + i),然后将该值解引用为指向 std::string.
的指针
通过写入 (*a)[i]
,您将得到以下计算:
*(*(&names) + i)
也就是
*(names + i)
,或
names[i]
对于一个问题,我必须使用动态分配和函数(仅使用指针变量)从 .txt 文件中读取名称并按词汇顺序对名称进行排序。但是,我什至无法让读取功能正常工作。这是它写的:
void readNames(std::string* a[])
{
std::ifstream fin;
fin.open("names.txt");
for (int i = 0; i < 7; ++i)
{
fin >> *(a[i]);
std::cout << *a[i];
}
}
这是我在 main 中的调用方式:
std::string* names;
names = new std::string[7];
readNames(&names);
但是,当我 运行 这样做时,我得到了错误:
抛出异常:读取访问冲突。 这是 0xCCCCCCCC。
并显示了这个功能(不确定是否有帮助):
void _Check_offset(const size_type _Off) const { // checks whether _Off is in the bounds of [0, size()]
if (_Mysize < _Off) {
_Xran();
}
}
如果有人能帮我解决这个问题,我将不胜感激,谢谢!
为了详细说明 WhozCraig 的评论,我们假设如下:
names
驻留在栈上,所以我们给它地址 0x7f001000.- 你分配的字符串数组驻留在堆上,所以我们给它地址0x1000
- 您将该地址分配给
names
,因此地址 0x7f001000 包含值 0x1000。
里面readNames
,a
是names
的地址,所以表达式*(a[i])
可以改写为:
*(*(&names + i))
对于 i=0,这是可行的。您基本上取消引用 a
一次以获取数组的开头,然后再次获取对第一个分配的 std::string
.
对于任何其他 i,您访问堆栈上的数据 (0x7f001000 + i),然后将该值解引用为指向 std::string.
的指针通过写入 (*a)[i]
,您将得到以下计算:
*(*(&names) + i)
也就是
*(names + i)
,或
names[i]