我正在用 C++ 进行一个小的编程练习。目标是用 2 的前 32 次幂初始化一个数组,然后输出它们。 使用普通的 for 循环没有问题,但我尝试使用 C++11 标准中引入的基于范围的 for 循环。 在编译期间,我收到警告“基于范围的 for 循环是 C++11 扩展 [-Wc++11-extensions]”。 运行程序我得到错误“Segmentation fault: 11”,没有任何进一步的输出。
我已经知道 elem 变量以某种方式损坏了,但我不知道如何损坏。 希望你能帮助 n00b :)
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int LAENGE = 32;
long potenzen[LAENGE];
for(int elem : potenzen)
{
potenzen[elem] = pow(2.0, (double) (elem + 1));
}
for(int elem : potenzen)
{
cout << endl;
cout << potenzen[elem];
}
cout << endl;
return 0;
}
最佳答案
elem
在 potenzen
中分配了值 ,不是指数。 cout << elem;
是你想要的而不是打印数组的元素。为了填充数组,只需使用整数索引:
for (int i = 0; i < LENGTH; i++) { // ProTip #1: use English identifiers
array[i] = 2 << i; // ProTip #2: don't use `pow()` when working with integers
}
至于编译器警告:使用 -std=c++11
或 -std=c++0x
编译时标记以告诉编译器您打算使用 C++11 功能(假设您使用 GCC 或 clang——我不确定其他编译器。)
关于c++ - 段错误 : 11; range-based for loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18802696/