0

I have really basic question: Is that possible to convert int variable into constant, so I can initialize an array with given length statically (without pointers and new function). I am just curious, I know how to do it dynamically. Thanks

5
  • 3
    No, arrays need to know their size at compile time, theres nothing you can do at runtime to get around this issue. Commented Dec 10, 2014 at 17:17
  • Even if you found a way to work around it I have doubts the compiler would treat it as anything other than a variable-length array. Commented Dec 10, 2014 at 17:18
  • I am asking this, because I write CUDA programm. I want to use Shared memory and I'm not sure I can allocate it dynamically, there are some issues with dynamical allocation. Commented Dec 10, 2014 at 17:21
  • possible duplicate: stackoverflow.com/questions/14417318/cuda-new-delete Commented Dec 10, 2014 at 17:29
  • You can use alloca() to allocate a dynamic amount of memory on the stack in standard C and C++; check if CUDA supports it. Note that the returned pointer has its lifetime bound to the function in which alloca() is called, so the pointer becomes invalid when that function returns! Commented Dec 10, 2014 at 17:39

2 Answers 2

3

The size of an array must be a compile time constant, i.e. it must be known at compile-time. You obviously cannot convert something that is not known at compile time to something that is known at compile time because, well, you do not know it at compile time. How would that even work, do you expect the value to travel back in time?

If you do not know the desired size at compile time, use std::vector, not pointers and new.

Sign up to request clarification or add additional context in comments.

Comments

0

In the comment, you mention using shared memory. In general, std::vector is good for dynamically sized arrays. The class has an allocator and will grow the array and copy the elements when needed. That won't work for shared memory. Shared memory is a special case where the array size is fixed and the pointer is determined at run-time.

Even if you knew the size of the shared memory segment at compile-time, a statement like:

   char myData[100];

would allocate memory for the myData. Shared memory is a good case for using a pointer and then treating it like an array. For example, you could do this:

   int total = 0;
   int n = getSizeOfSharedMemorySomehow();
   char *myData = getSharedMemoryPointerSomehow();
   for (int i = 0; i < n; i++)
       total += myData[i];

Comments

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.