【发布时间】:2022-01-19 13:10:33
【问题描述】:
我在搜索一些与 VirtualAlloc 相关的代码时,偶然发现了这段代码:
#include<windows.h>
#include<iostream>
using namespace std;
int main() {
size_t in_num_of_bytes,i;
cout<<"Please enter the number of bytes you want to allocate:";
cin>>in_num_of_bytes;
LPVOID ptr = VirtualAlloc(NULL,in_num_of_bytes,MEM_RESERVE | MEM_COMMIT,PAGE_READWRITE); //reserving and commiting memory
if(ptr){
char* char_ptr = static_cast<char*>(ptr);
for(i=0;i<in_num_of_bytes;i++){ //write to memory
char_ptr[i] = 'a';
}
for(i=0;i<in_num_of_bytes;i++){ //print memory contents
cout<<char_ptr[i];
}
VirtualFree(ptr, 0, MEM_RELEASE); //releasing memory
}else{
cout<<"[ERROR]:Could not allocate "<<in_num_of_bytes<<" bytes of memory"<<endl;
}
return 0;
}
这是我试图理解的一段代码。但是,我对以下行感到困惑:
char* char_ptr = static_cast<char*>(ptr);
我不确定为什么需要这条线。它有什么作用?
【问题讨论】:
-
因为 C++ 和 C 是不同的语言。在 C 中,
void *可以自动转换为任何指针类型,因为动态分配使用malloc和free。在 C++ 中,动态分配使用new和delete,通常不需要指针转换,因此必须明确地转换为void *。