gpt4 book ai didi

c++是否明确定义了将静态数组转换为指针然后递增该指针以访问元素?

转载 作者:行者123 更新时间:2023-12-01 14:14:57 26 4
gpt4 key购买 nike

下面的代码可以工作,但是它的定义是否明确?

const int N = 8;
int arr[N];
int* ptr = arr;
for(int i=0; i<N; i++) {
std::cout << ptr[i] << "\n";
}

第二个问题:

使用编译为 C++14 的 -O2 优化运行此代码 http://cpp.sh/7eagy给我以下输出:

1
0
0
0
4196448
0
4196198
0

而以下版本:

const int N = 8;
int arr[N] = {};
int* ptr = arr;
for(int i=0; i<N; i++) {
std::cout << ptr[i] << "\n";
}

给予

0
0
0
0
0
0
0
0

表示没有 = {} arr 不是零初始化的,而是根据 https://en.cppreference.com/w/cpp/language/zero_initialization应该是

至少给定的示例说明:双 f[3];//零初始化为三个 0.0

那么我在第一个版本中没有得到零的原因是什么?

最佳答案

在第一个版本中,你有

int arr[N];

而不是第二个版本:

int arr[N] = {};

与指针访问无关。您链接的页面说:

double f[3]; // zero-initialized to three 0.0's

但这只适用于静态变量。你的是一个局部的、非静态的变量(我们没有看到完整的代码,但由于它与 for 处于相同的范围,我们可以推断出它)。在标准语中,它写成:

  1. For every named variable with static or thread-local storage duration that is not subject to constant initialization, before any other initialization.

关于c++是否明确定义了将静态数组转换为指针然后递增该指针以访问元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62920511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com