c++ - 段错误 : 11; range-based for loop

标签 c++ c++11 segmentation-fault

我正在用 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;
}

最佳答案

elempotenzen 中分配了 ,不是指数。 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/

相关文章:

c - 分段故障核心转储: Function that returns the next prime number

c++ - C : advantages and disadvantages 中的另一种字符串实现

c++ - 在C++中使用回调异步运行linux命令

c++ - C/C++ : sizeof(short), sizeof(int)、sizeof(long)、sizeof(long long) 等...在 32 位机器上与在 64 位机器上

C++ 如何基于部分特化创建 std::tuple 类型?

c++ - 第二次调用函数时出现段错误?

c++ - 如何在 C++ 中使用 system() 函数打开应用程序

c++ - (char *) (msg +1) 这个 +1 带我们去哪里?

c++ - 检查数组中消息的最有效方法

c - c程序的段错误