logo search
CSharp_Prog_Guide

Доступ к элементу массива с использованием указателя

В небезопасной среде можно получить доступ к элементу в памяти посредством доступа к элементу указателя

char* charPointer = stackalloc char[123];

for (int i = 65; i < 123; i++)

{

charPointer[i] = (char)i; //access array elements

}

Выражение в квадратных скобках должно быть явным образом преобразуемым в int, uint, long или ulong. Операция p[e] эквивалентна *(p+e). Как в C и C++, доступ к элементу указателя не проверяет ошибки, выходящие за пределы.

Пример

В этом примере 123 элемента памяти назначаются массиву символов charPointer. Массив используется для отображения букв нижнего регистра и букв верхнего регистра в двух циклах for.

Обратите внимание, что выражение charPointer[i] эквивалентно выражению *(charPointer + i), и можно получить одинаковый результат, используя любое из этих двух выражений.

-----

Manipulating Pointers

How to: Increment and Decrement Pointers

Use the increment and the decrement operators, ++ and --, to change the pointer location by sizeof (pointer-type) for a pointer of type pointer-type*. The increment and decrement expressions take the following form:

++p;

P++;

--p;

p--;

The increment and decrement operators can be applied to pointers of any type except the type void*.

The effect of applying the increment operator to a pointer of the type pointer-type is to add sizeof (pointer-type) to the address that is contained in the pointer variable.

The effect of applying the decrement operator to a pointer of the type pointer-type is to subtract sizeof (pointer-type) from the address that is contained in the pointer variable.

No exceptions are generated when the operation overflows the domain of the pointer, and the result depends on the implementation.

Example

In this example, you step through an array by incrementing the pointer by the size of int. With each step, you display the address and the content of the array element.

// compile with: /unsafe

class IncrDecr

{

unsafe static void Main()

{

int[] numbers = {0,1,2,3,4};

// Assign the array address to the pointer:

fixed (int* p1 = numbers)

{

// Step through the array elements:

for(int* p2=p1; p2<p1+numbers.Length; p2++)

{

System.Console.WriteLine("Value:{0} @ Address:{1}", *p2, (long)p2);

}

}

}

}

Value:0 @ Address:12860272

Value:1 @ Address:12860276

Value:2 @ Address:12860280

Value:3 @ Address:12860284

Value:4 @ Address:12860288