I am getting my head around void pointers in C++ and as an exercise have written the following code:
void* routine(void* number){
int n = (int)number;
int* np = (int*)number;
cout<<"void pointer: "<<number<<endl;
cout<<"casted int pointer: "<<np<<endl;
cout<<"int pointer content: "<<*np<<endl;
return (void*)NULL;
}
int main(){
int num = 1;
routine((void*)num);
}
This breaks in runtime as the pointer np
, casted from void*
to int*
is dereferenced.
I attempt to pass the argument number
as a void pointer and dereference its value inside the function. Arithmetic on void pointers are illegal, therefore what I try to do is cast the pointer to an int*
and attempt to dereference this casted copy.
I somewhat expect this not to work, but if that were the case I would also expect some sort of compiler error as is the case when this attempt is made without the int*
cast. The reason I sort of expect it to work is that the casted pointer retains the original void pointer address, meaning that after the cast it appears to be just a regular memory address, which I see no reason to be inaccessible by regular dereference. The n
variable is a copy of the referenced value, but is just that - I cannot change the actual value in the memory address.
Is this possible with a void pointer? What am I missing?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…