How to: Increment and Decrement 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

 


Управление указателями

Увеличение и уменьшение указателей

Используйте операторы увеличения и уменьшения, ++ и --, для изменения положения указателя на значение sizeof (pointer-type) применительно к указателю, имеющему тип "тип указателя*". Выражения увеличения и уменьшения принимают следующую форму:

++p; P++; --p; p--;

Операторы увеличения и уменьшения можно применять к указателям любого типа, кроме типа void*.

Результатом применения оператора увеличения к указателю типа pointer-type является добавление значения sizeof (pointer-type) к адресу, содержащемуся в переменной указателя.

Результатом применения оператора уменьшения к указателю типа pointer-type является вычитание значения sizeof (pointer-type) из адреса, содержащегося в переменной указателя.

При переполнении в результате выполнения этой операции домена указателя исключений не генерируется, а результат зависит от конкретной реализации.

Пример

В этом примере выполняется перемещение по массиву путем увеличения значения переменной указателя на размер типа int. После выполнения каждого шага отображается адрес и содержимое элемента массива.

ß--------


Arithmetic Operations on Pointers

This topic discusses using the arithmetic operators + and - to manipulate pointers.

Note:
You cannot perform any arithmetic operations on void pointers.

Adding and Subtracting Numeric Values to or From Pointers

You can add a value n of type int, uint, long, or ulong to a pointer, p,of any type except void*. The result p+n is the pointer resulting from adding n * sizeof(p) to the address of p. Similarly, p-n is the pointer resulting from subtracting n * sizeof(p) from the address of p.

Subtracting Pointers

You can also subtract pointers of the same type. The result is always of the type long. For example, if p1 and p2 are pointers of the type pointer-type*, then the expression p1-p2 results in:

((long)p1 - (long)p2)/sizeof(pointer_type)

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

Example

// compile with: /unsafe
class PointerArithmetic { unsafe static void Main() { int* memory = stackalloc int[30]; long* difference; int* p1 = &memory[4]; int* p2 = &memory[10];   difference = (long*)(p2 - p1);   System.Console.WriteLine("The difference is: {0}", (long)difference); } }

Output

The difference is: 6

 



Поделиться:


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

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