代码之家  ›  专栏  ›  技术社区  ›  Noitidart

使用const int by reference创建静态数组

c++
  •  0
  • Noitidart  · 技术社区  · 6 年前

    我想把一排双打运动员 pi_sequence 然后返回指向它的指针。然后我想打印出它的值。我试过了,但我得到了错误 storage size of ests is not constant :

    #include <iostream>
    #include <stdlib.h>
    
    
    double* pi_sequence(const int& len)
    {
      static double ests[len];
      ests[0] = 1.11;
      ests[1] = 2.22;
      return ests; // address of?
    }
    
    int main() {
    
      double* ests = pi_sequence();
      std::cout << "will write to file: " << ests[0]  << std::endl;
    
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   eerorika    6 年前

    使用const int by reference创建静态数组

    不可能。具有非动态存储的所有数组的长度必须是编译时常量。

    可以有一个静态向量:

    assert(len >= 2);
    static std::vector<double> ests(len);
    // ...
    return ests.data();