简体   繁体   English

关于C ++中的stl填充功能的问题

[英]question on stl fill function in C++

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: 如果我想用“ -1”填充它,这是正确的方法:

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. 如果我将x [2] [55]更改为x [1] [54],则可以使用,但不会初始化数组的最后一个元素。

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"

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: 简单的答案是您执行以下操作:

&x[1][55]

Let's consider what a 2d array x[N][M] is laid out in memory 让我们考虑一下二维数组x[N][M]在内存中的布局

[0][0] [0][1] ... [0][M-1] [1][0] [1][1] ... [1][M-1] [N-1][0] .. [N-1][M-1]

So, the very last element is [N-1][M-1] and the first element beyond is [N-1][M] . 因此,最后一个元素为[N-1][M-1] ,之后的第一个元素为[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. 如果您使用[N][M]的地址,那么您将远远超过结尾并且覆盖了很多内存。

Another way to calculate the first address beyond the end is to use sizeof. 计算末尾第一个地址的另一种方法是使用sizeof。

&x[0][0] + sizeof(x) / sizeof(std::string);

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. 将2D数组重新解释为1D数组会导致未定义的行为,因为您实际上是在尝试访问1D x[0]数组的边界之外的内容。

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). 可以将其指定为&x[1][55]&x[2][0] (都是相同的地址)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM