0

I am trying to cretate an array of doubles in pi_sequence and then return a pointer to it. Then I want to print out its values. I tried this but I get the error 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;

}
5
  • 1
    That's because the size of a static array needs to be a known compile time constant. But your implementation seems to assume len is always 2 anyway, since you assign to ests[0] and ests[1] so I have a hard time understanding what you actually want to do. Commented Jan 16, 2019 at 20:21
  • @FrançoisAndrieux its a very simplified case. My case is bigger. Is it possible to create static array without compile time constant? Or is it possible to return array another way from that fucntion? Commented Jan 16, 2019 at 20:22
  • Consider using std::vector Commented Jan 16, 2019 at 20:24
  • You will necessarily need to know at compile time the size of the array, or at least deduce it at compile time. It cannot depend on user input. constexpr and templates will let you do sophisticated calculations are compile time. But if you need it to depend on user input you will need to use another approach, maybe just returning an std::vector<double>. Commented Jan 16, 2019 at 20:24
  • "Is it possible to create static array without compile time constant?" - NO. In order to create a fixed-length array, the compiler needs to know the exact array size to use. Hence a compile-time constant is required. Otherwise, you have to allocate the array dynamically at runtime, using new[] or std::vector Commented Jan 16, 2019 at 20:51

1 Answer 1

2

Use const int by reference to create static array

Is not possible. The length of all arrays which have non-dynamic storage must be a compile time constant.

You can have a static vector:

assert(len >= 2);
static std::vector<double> ests(len);
// ...
return ests.data(); 
Sign up to request clarification or add additional context in comments.

3 Comments

May you please show how to use that in a function like above.
@Noitidart just replace the contents of your function with what I show. You can replace the // ... with whatever you have between declaration of ests and return.
@Noitidart given the implementation that I show, it should be double*.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.