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
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 |
Управление указателями
Дата добавления: 2019-03-09; просмотров: 219; Мы поможем в написании вашей работы! |
Мы поможем в написании ваших работ!