关于C中stl填充函数的问题++

发布于 2024-08-20 17:52:40 字数 413 浏览 5 评论 0原文

假设我有一个像这样的数组:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猥琐帝 2024-08-27 17:52:40

因为当你有一个多维数组时,第一个元素之外的地址计算起来有点混乱。简单的答案是你这样做:

&x[1][55]

让我们考虑一下二维数组 x[N][M] 在内存中的布局

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

所以,最后一个元素是 [N-1][M -1],超出的第一个元素是[N-1][M]。如果你获取[N][M]的地址,那么你会远远超出末尾并覆盖大量内存。

另一种计算超出末尾的首地址的方法是使用 sizeof。

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

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

[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]. 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.

&x[0][0] + sizeof(x) / sizeof(std::string);
爱人如己 2024-08-27 17:52:40

从形式和迂腐的角度来看,这是违法的。将 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文