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
2 Answers
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.
Comments
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];
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 whichalloca()is called, so the pointer becomes invalid when that function returns!