Reputation: 125
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
Upvotes: 0
Views: 216
Reputation: 748
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];
Upvotes: 0
Reputation: 50111
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
.
Upvotes: 3