[英]Error when writing from file into pointer of string array (read access violation)? CPP
For a problem, I have to use dynamic allocation and functions (using pointer variables only) to read the names from the .txt file and sort the names in lexical order.对于一个问题,我必须使用动态分配和函数(仅使用指针变量)从 .txt 文件中读取名称并按词法顺序对名称进行排序。 However, I cannot even get the read function to work properly.
但是,我什至无法使读取功能正常工作。 This is what it wrote:
它是这样写的:
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];
}
}
This is how I called it in main:这就是我在 main 中调用它的方式:
std::string* names;
names = new std::string[7];
readNames(&names);
However, when I run this I get the error:但是,当我运行它时,我收到错误:
Exception thrown: read access violation.抛出异常:读取访问冲突。 this was 0xCCCCCCCC.
这是 0xCCCCCCCC。
And this function is displayed(not sure if this helps):并显示此功能(不确定这是否有帮助):
void _Check_offset(const size_type _Off) const { // checks whether _Off is in the bounds of [0, size()]
if (_Mysize < _Off) {
_Xran();
}
}
If anyone can help me with this I would relly appreciate it, thank you!如果有人能帮我解决这个问题,我将不胜感激,谢谢!
To elaborate on WhozCraig's comment, let us assume the following:为了详细说明 WhozCraig 的评论,让我们假设以下内容:
names
resides on the stack, so we give it address 0x7f001000. names
驻留在堆栈中,所以我们给它地址 0x7f001000。names
, so address 0x7f001000 contains the value 0x1000.names
,因此地址 0x7f001000 包含值 0x1000。 Inside readNames
, a
is the address of names
, so the expression *(a[i])
can be rewritten as:在
readNames
, a
是names
的地址,所以表达式*(a[i])
可以改写为:
*(*(&names + i))
For i=0, this works out.对于 i=0,这是可行的。 You basically dereference
a
once to get the start of the array, and then again to get a reference to the first allocated std::string
.你基本上取消引用
a
一次获取数组的开始,然后再次去的第一个分配的参考std::string
。
For any other i, you access data on the stack (0x7f001000 + i) and then dereference that value as a pointer to a std::string.对于任何其他 i,您访问堆栈 (0x7f001000 + i) 上的数据,然后将该值取消引用为指向 std::string 的指针。
By writing (*a)[i]
you get the following calculation instead:通过编写
(*a)[i]
您可以得到以下计算:
*(*(&names) + i)
which is这是
*(names + i)
, or , 或者
names[i]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.