Неявные преобразования указателей



Из В
Любой тип указателя void*
null Любой тип указателя

Явное преобразование указателя используется для выполнения преобразований, для которых невозможно неявное преобразование, с помощью выражения приведения. В следующей таблице приведено описание этих преобразований.

Явные преобразования указателей

Из В
Любой тип указателя Любой другой тип указателя
sbyte, byte, short, ushort, int, uint, long или ulong Любой тип указателя
Любой тип указателя sbyte, byte, short, ushort, int, uint, long или ulong

 


Example

In the following example, a pointer to int is converted to a pointer to byte. Notice that the pointer points to the lowest addressed byte of the variable. When you successively increment the result, up to the size of int (4 bytes), you can display the remaining bytes of the variable.

// compile with: /unsafe
class ClassConvert { static void Main() {    int number = 1024;      unsafe    {        // Convert to byte:        byte* p = (byte*)&number;          System.Console.Write("The 4 bytes of the integer:");          // Display the 4 bytes of the int variable:        for (int i = 0 ; i < sizeof(int) ; ++i)        {            System.Console.Write(" {0:X2}", *p);               // Increment the pointer:            p++;        }        System.Console.WriteLine();        System.Console.WriteLine("The value of the integer: {0}", number);    } } }

Output

The 4 bytes of the integer: 00 04 00 00

The value of the integer: 1024

 


Пример

В следующем пример указатель на int преобразуется в указатель на byte. Обратите внимание на то, что указатель указывает на наименьший адресуемый байт переменной. При последовательном увеличении результата до размера int (4 байта) можно отобразить оставшиеся байты переменной.

ß-----

 

 

Результат

The 4 bytes of the integer: 00 04 00 00

The value of the integer: 1024

 


Pointer Expressions

How to: Obtain the Value of a Pointer Variable

Use the pointer indirection operator to obtain the variable at the location pointed to by a pointer. The expression takes the following form, where p is a pointer type:

*p;

You cannot use the unary indirection operator on an expression of any type other than the pointer type. Also, you cannot apply it to a void pointer.

When you apply the indirection operator to a null pointer, the result depends on the implementation.

Example

In the following example, a variable of the type char is accessed by using pointers of different types. Note that the address of theChar will vary from run to run, because the physical address allocated to a variable can change.

// compile with: /unsafe
unsafe class TestClass { static void Main() {    char theChar = 'Z';    char* pChar = &theChar;    void* pVoid = pChar;    int* pInt = (int*)pVoid;      System.Console.WriteLine("Value of theChar = {0}", theChar);    System.Console.WriteLine("Address of theChar = {0:X2}",(int)pChar);    System.Console.WriteLine("Value of pChar = {0}", *pChar);    System.Console.WriteLine("Value of pInt = {0}", *pInt); } }

 

Value of theChar = Z Address of theChar = 12F718 Value of pChar = Z Value of pInt = 90

 


Выражения указателей

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

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

 


Получение адреса переменной

Чтобы получить адрес унарного выражения (которое оценивается как фиксированная переменная), используйте оператор address-of:

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

Оператор address-of можно применять только к переменной. Если переменная является перемещаемой, можно использовать фиксированное предложение, чтобы временно зафиксировать переменную перед получением ее адреса.

Разработчик отвечает за инициализацию переменной. Если переменная не будет инициализирована, на компиляторе не будет отображено сообщение об ошибке.

Невозможно получить адрес константы или переменной.

Пример

В данном примере указатель на int, p объявляется и ему присваивается адрес целочисленной переменной number. Переменная number инициализируется в результате присвоения *p. Если в тексте кода закомментировать присвоение, то инициализация переменной number будет удалена, однако при компиляции не возникнет сообщений об ошибках. Обратите внимание на применение оператора доступа члена -> для получения и отображения адреса, хранящегося в указателе.

ß-----


Дата добавления: 2019-03-09; просмотров: 231; Мы поможем в написании вашей работы!

Поделиться с друзьями:






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