关于C中stl填充函数的问题++
假设我有一个像这样的数组:
string x[2][55];
如果我想用“-1”填充它,这是正确的方法吗:
fill(&x[0][0],&x[2][55],"-1");
当我尝试运行它时崩溃了。如果我将 x[2][55] 更改为 x[1][54] 它可以工作,但不会初始化数组的最后一个元素。
这是一个例子来证明我的观点:
string x[2][55];
x[1][54] = "x";
fill(&x[0][0],&x[1][54],"-1");
cout<<x[1][54]<<endl; // this print's "x"
Let's say I have an array like this:
string x[2][55];
If I want to fill it with "-1", is this the correct way:
fill(&x[0][0],&x[2][55],"-1");
That crashed when I tried to run it. If I change x[2][55] to x[1][54] it works but it doesn't init the last element of the array.
Here's an example to prove my point:
string x[2][55];
x[1][54] = "x";
fill(&x[0][0],&x[1][54],"-1");
cout<<x[1][54]<<endl; // this print's "x"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为当你有一个多维数组时,第一个元素之外的地址计算起来有点混乱。简单的答案是你这样做:
让我们考虑一下二维数组
x[N][M]
在内存中的布局所以,最后一个元素是
[N-1][M -1]
,超出的第一个元素是[N-1][M]
。如果你获取[N][M]
的地址,那么你会远远超出末尾并覆盖大量内存。另一种计算超出末尾的首地址的方法是使用 sizeof。
Because when you have a multi-dimensional array, the address beyond the first element is a little confusing to calculate. The simple answer is you do this:
Let's consider what a 2d array
x[N][M]
is laid out in memorySo, the very last element is
[N-1][M-1]
and the first element beyond is[N-1][M]
. If you take the address of[N][M]
then you go very far past the end and you overwrite lots of memory.Another way to calculate the first address beyond the end is to use sizeof.
从形式和迂腐的角度来看,这是违法的。将 2D 数组重新解释为 1D 数组会导致未定义的行为,因为您实际上是在尝试访问超出其边界的 1D
x[0]
数组。实际上,这是可行的(尽管某些代码分析工具可能会将此报告视为违规)。但为了正确指定指向“最后一个元素之后的元素”的指针,您必须小心。它可以指定为
&x[1][55]
或&x[2][0]
(两者是相同的地址)。From the formal and pedantic point of view, this is illegal. Reinterpreting a 2D array as a 1D array results in undefined behavior, since you are literally attempting to access 1D
x[0]
array beyond its boundary.In practice, this will work (although some code analysis tools might catch an report this as a violation). But in order to specify the pointer to the "element beyond the last" correctly, you have to be careful. It can be specified as
&x[1][55]
or as&x[2][0]
(both are the same address).