logo
CSharp_Prog_Guide

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

Для осуществления доступа к члену структуры, объявленной в небезопасном контексте, можно использовать оператор доступа к члену, как показано в следующем примере, где p — это указатель на структуру содержащую член x.

CoOrds* p = &home;

p -> x = 25; //member access operator ->

Пример

В этом примере объявлена структура CoOrds, содержащая две координаты x и y, после чего создан ее экземпляр. С помощью оператора доступа к членам -> и указателя на экземпляр home координатам x и y присваиваются значения.

Примечание.

Обратите внимание, что выражение p->x эквивалентно выражению (*p).x, и можно получить одинаковый результат, используя любое из этих двух выражений.

----

How to: Access an Array Element with a Pointer

In an unsafe context, you can access an element in memory by using pointer element access, as shown in the following example:

char* charPointer = stackalloc char[123];

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

{

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

}

The expression in square brackets must be implicitly convertible to int, uint, long, or ulong. The operation p[e] is equivalent to *(p+e). Like C and C++, the pointer element access does not check for out-of-bounds errors.

Example

In this example, 123 memory locations are allocated to a character array, charPointer. The array is used to display the lowercase letters and the uppercase letters in two for loops.

Notice that the expression charPointer[i] is equivalent to the expression *(charPointer + i), and you can obtain the same result by using either of the two expressions.

// compile with: /unsafe

class Pointers

{

unsafe static void Main()

{

char* charPointer = stackalloc char[123];

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

{

charPointer[i] = (char)i;

}

// Print uppercase letters:

System.Console.WriteLine("Uppercase letters:");

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

{

System.Console.Write(charPointer[i]);

}

System.Console.WriteLine();

// Print lowercase letters:

System.Console.WriteLine("Lowercase letters:");

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

{

System.Console.Write(charPointer[i]);

}

}

}

Uppercase letters:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Lowercase letters:

abcdefghijklmnopqrstuvwxyz