Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are stack based arrays possible in C#?

Let's say, hypothetically (read: I don't think I actually need this, but I am curious as the idea popped into my head), one wanted an array of memory set aside locally on the stack, not on the heap. For instance, something like this:

private void someFunction()
{
    int[20] stackArray; //C style; I know the size and it's set in stone
}

I'm guessing the answer is no. All I've been able to find is heap based arrays. If someone were to need this, would there be any workarounds? Is there any way to set aside a certain amount of sequential memory in a "value type" way? Or are structs with named parameters the only way (like the way the Matrix struct in XNA has 16 named parameters (M11-M44))?

like image 416
Bob Avatar asked Mar 16 '10 16:03

Bob


People also ask

Are arrays on the stack in C?

Unlike Java, C++ arrays can be allocated on the stack. Java arrays are a special type of object, hence they can only be dynamically allocated via "new" and therefore allocated on the heap.

Can array be stored in stack?

Yes, the whole array is pushed on stack.

Is stack array based?

The array-based stack implementation is essentially a simplified version of the array-based list. The only important design decision to be made is which end of the array should represent the top of the stack. One choice is to make the top be at position 0 in the array.

Are arrays in heap or stack?

Memory is allocated in Heap are for the Array in Java. In Java reference types are stored in the Heap area. As arrays are also reference types, (they can be created using the “new” keyword) they are also stored in the Heap area.


1 Answers

What you want is stackalloc; unfortunately, you can only use this in unsafe code, which means it won't run in a limited permissions context.

You could also create a struct with the necessary number of variables in it for each element type, but you would need a new type for each size of 'array' you wanted to use

like image 53
thecoop Avatar answered Sep 30 '22 06:09

thecoop