[英]Typecasting of Pointers in C++
假設指針大小為 4
#include<stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60};
int *ptr1 = arr;
int *ptr2 = arr + 5;
printf("Number of bytes between two pointers are: %d",
(char*)ptr2 - (char*) ptr1);
return 0;
}
輸出:20
在這個程序中,為什么在類型轉換中將輸出打印為 sizeof 指針? 為什么不打印 5?
在這個程序中,為什么在類型轉換中將輸出打印為 sizeof 指針? 為什么不打印 5?
到char*
的演員表就是這樣做的。
只要指針是int*
類型, ptr2
和ptr1
之間的偏移量就是5
。 當您顯式地將指針強制轉換為char*
,您是在要求程序計算指針之間的偏移量,就好像它們是char*
。 你的程序說,它是20
,它等於5*sizeof(int)
。
數組的每個元素在內存中占用 4 個字節的空間。
因此,計算可以如下進行:
char_type_cast of (pointer2 - pointer1)
(bytes_between_pointers / 4)
int_type_cast of (pointer2 - pointer1)
工作代碼:
#include<stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60};
int *ptr1 = arr;
int *ptr2 = arr + 5;
/*
1 pointer = 4 bytes
Byte-sized spaces = char_type_cast of (ptr2 - ptr1)
Pointer-sized spaces = byte_spaces / 4
Integer-sized spaces = int_type_cast of (ptr2 - ptr1)
*/
int byteSpaces = ((char*)ptr2 - (char*)ptr1);
int pointerSpaces = (byteSpaces / 4);
int integerSpaces = ((int*)ptr2 - (int*)ptr1);
printf("Pointer 1 = %d\n", *ptr1);
printf("Pointer 2 = %d\n", *ptr2);
printf("\nByte sized spaces between two pointers = %d\n", byteSpaces);
printf("\nPointer sized spaces between pointers = %d\n", pointerSpaces);
printf("\nInteger sized spaces between pointers = %d\n", integerSpaces);
return 0;
}
輸出:
Pointer 1 = 10
Pointer 2 = 60
Byte sized spaces between two pointers = 20
Pointer sized spaces between pointers = 5
Integer sized spaces between pointers = 5
除了@R sahu 的回答,看看這段代碼並通過調試器運行它。 你會發現t1 = '\\n'
和t2 = '<'
。 減法是20
代碼:
#include<stdio.h>
#include <iostream>
int main() {
int arr[] = { 10, 20, 30, 40, 50, 60 };
int* ptr1 = arr;
int* ptr2 = arr + 5;
auto* t1 = ( char* ) ptr1;
auto* t2 = ( char* ) ptr2;
std::cout << ( int ) (t1 - t2);
printf("Number of bytes between two pointers are: %d",
( char* ) ptr2 - ( char* ) ptr1);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.