1

I'm working on a small programming exercise in C++. Goal is to initiate an array with the first 32 exponentations of 2 and to output them afterwards. Using a normal for loop there's no problem but I tried to use the range-based for loop introduced in the C++11 standard. During compilation I get the warning "range-based for loop is a C++11 extension [-Wc++11-extensions]". Running the program I get the error "Segmentation fault: 11" without any further output.

I got already that the elem variable somehow is broken but I don't know how. Hope you can help a 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;
}
4

3 回答 3

7

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++11or-std=c++0x标志告诉编译器您打算使用 C++11 功能(假设您使用 GCC 或 clang——我不确定其他编译器。)

于 2013-09-14T14:19:25.743 回答
3

Ranged for 循环将为您提供元素值,而不是元素索引。

    potenzen[elem] = pow(2.0, (double) (elem + 1));

应该

for(int i = 0; i < LAENGE; i++)
  potenzen[i] = 2 << i;

(对于转移,请参阅 H2CO3 的答案和他的评论如下)

请注意,您不能在此处使用 foreach 循环:

for(int& elem : potenzen)
{
    elem = pow(2.0, (double) (elem + 1));
}

当您访问elem语句右侧的未初始化值时。

还:

for(int elem : potenzen)
{
    cout << endl;
    cout << potenzen[elem];
}

应该

for(int elem : potenzen)
{
    cout << endl;
    cout << elem;
}

aselem将包含数组值。

于 2013-09-14T14:20:28.653 回答
1

上面的答案正确地指出了代码中的问题,但是如果你想将数组索引作为元素值,你必须设置它们,否则它们将被初始化为不确定的(垃圾)值;以下代码也是一个与您尝试做的有点相似的解决方案:

#include <iostream>
#include <algorithm>

int main()
{
  constexpr auto count = 32;
  unsigned long long values[count] = { }; // initialise elements to 0
  auto i = 0;
  // fill them with their respective index values
  std::generate_n(values, count, [&i] { return i++; });
  for(auto &x : values)
  {
    // without casting the literal 2 would be treated as an int
    x = static_cast<unsigned long long>(2) << x;
    std::cout << x << std::endl;
  }
  return 0;
}

我使用unsigned long long了而不是long,因为在许多系统上 long 的大小是 4 个字节,但是 2^32 = 4294967296 = 0x100000000 即需要 33 位。此外,由于我们知道所有值都将是正数,因此将其设为无符号更有意义。

于 2013-09-14T17:10:39.940 回答