logo search
CSharp_Prog_Guide

Выражения указателей Получение значения переменной указателя

Косвенный оператор указателя служит для получения переменной в расположении, на которое указывает указатель. Выражение имеет следующий вид (где p — тип указателя):

*p;

Невозможно использовать унарный косвенный оператор с выражениями какого-либо типа, за исключением типа указателя. Кроме того, его невозможно применить к пустому указателю.

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

Пример

В следующем примере к переменной типа char получают доступы указатели различных типов. Обратите внимание, что адрес theChar будет изменяться в каждом случае, поскольку физический адрес переменной может изменяться.

----

How to: Obtain the Address of a Variable

To obtain the address of a unary expression, which evaluates to a fixed variable, use the address-of operator:

int number;

int* p = &number; //address-of operator &

The address-of operator can only be applied to a variable. If the variable is a moveable variable, you can use the fixed statement to temporarily fix the variable before obtaining its address.

It is your responsibility to ensure that the variable is initialized. The compiler will not issue an error message if the variable is not initialized.

You cannot get the address of a constant or a value.

Example

In this example, a pointer to int, p, is declared and assigned the address of an integer variable, number. The variable number is initialized as a result of the assignment to *p. If you make this assignment statement a comment, the initialization of the variable number will be removed, but no compile-time error is issued. Notice the use of the Member Access operator -> to obtain and display the address stored in the pointer.

// compile with: /unsafe

class AddressOfOperator

{

static void Main()

{

int number;

unsafe

{

// Assign the address of number to a pointer:

int* p = &number;

// Commenting the following statement will remove the

// initialization of number.

*p = 0xffff;

// Print the value of *p:

System.Console.WriteLine("Value at the location pointed to by p: {0:X}", *p);

// Print the address stored in p:

System.Console.WriteLine("The address stored in p: {0}", p->ToString());

}

// Print the value of the variable number:

System.Console.WriteLine("Value of the variable number: {0:X}", number);

}

}

Value at the location pointed to by p: FFFF

The address stored in p: 65535

Value of the variable number: FFFF