How to: Access a Member with a Pointer 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

How to: Access a Member with a Pointer



To access a member of a struct that is declared in an unsafe context, you can use the member access operator as shown in the following example in which p is a pointer to a struct that contains a member x.

CoOrds* p = &home; p -> x = 25; //member access operator ->

Example

In this example, a struct, CoOrds, that contains the two coordinates x and y is declared and instantiated. By using the member access operator -> and a pointer to the instance home, x and y are assigned values.

Note:
Notice that the expression p->x is equivalent to the expression (*p).x, and you can obtain the same result by using either of the two expressions.
// compile with: /unsafe

 

struct CoOrds { public int x; public int y; }   class AccessMembers { static void Main() { CoOrds home;   unsafe { CoOrds* p = &home; p->x = 25; p->y = 12;   System.Console.WriteLine("The coordinates are: x={0}, y={1}", p->x, p->y); } } }

 


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

Для осуществления доступа к члену структуры, объявленной в небезопасном контексте, можно использовать оператор доступа к члену, как показано в следующем примере, где 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

 


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

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

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



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 95; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.145.191.169 (0.004 с.)