Csharp/C Sharp/Language Basics/stackalloc — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 11:39, 26 мая 2010
Содержание
allocates 26 characters on the stack the for loop assigns alphabetic characters to each element
using System;
public unsafe class Starter {
public static void Main() {
char* pChar = stackalloc char[26];
char* _pChar = pChar;
for (int count = 0; count < 26; ++count) {
(*_pChar) = (char)(((int)("A")) + count);
++_pChar;
}
for (int count = 0; count < 26; ++count) {
Console.Write(pChar[count]);
}
}
}
Invalid Cast Exceptions with Implicit Operators
public class TestClass
{
private MainClass MyMainClassObject;
public TestClass()
{
MyMainClassObject = new MainClass();
}
public static implicit operator MainClass(TestClass Source)
{
return Source.MyMainClassObject;
}
}
public class MainClass
{
public static void Main()
{
object MyObject;
MainClass MyMainClassObject;
MyObject = new TestClass();
MyMainClassObject = (MainClass)MyObject;
}
}
stackalloc Demo
using System;
class MainEntryPoint {
static unsafe void Main() {
Console.Write("How big an array do you want? \n> ");
string userInput = Console.ReadLine();
uint size = uint.Parse(userInput);
long* pArray = stackalloc long[(int)size];
for (int i = 0; i < size; i++)
pArray[i] = i * i;
for (int i = 0; i < size; i++)
Console.WriteLine("Element {0} = {1}", i, *(pArray + i));
}
}
Use stackalloc to allocate memory for integer array
using System;
class TestStackallocApp
{
unsafe public static void Foo(int* pa)
{
for (int* ip = pa; ip < (pa+5); ip++)
{
Console.WriteLine("value {0} at address: {1}", *ip, (int)ip);
}
}
static void Main(string[] args)
{
unsafe
{
int* pa = stackalloc int[5];
pa[0] = 12;
pa[1] = 34;
pa[2] = 56;
pa[3] = 78;
pa[4] = 90;
Foo(pa);
}
}
}