Void pointer

I

Ian Collins

howa said:
int i = 10;
void *j = &i;


How to print out the integer "10" ?
#include <iostream>

int main() { std::cout << 10 << std::endl; }

Or where you asking something else?
 
A

Alf P. Steinbach

* howa:
int i = 10;
void *j = &i;


How to print out the integer "10" ?

#include <iostream>
int main
{
std::cout << "10" << std::endl;
}

But I guess you meant how to access the variable "i" given the void*
pointer "j".

Technically the answer is to cast the pointer and dereference it,
*static_cast<int*>(j).

However, as a novice you should not use raw pointers at all, much less
void* pointers: what's the problem you're trying to use void* to solve?


Cheers, & hth.,

- ALf
 
H

howa

* howa:



Technically the answer is to cast the pointer and dereference it,
*static_cast<int*>(j).

However, as a novice you should not use raw pointers at all, much less
void* pointers: what's the problem you're trying to use void* to solve?

How does the following one compare with static_cast?

e.g. cout<< *(int*)j;


Howard
 
I

Ian Collins

howa said:
How does the following one compare with static_cast?

e.g. cout<< *(int*)j;
It's harder to search for in code and more likely to hide errors (the
compiler will reject inappropriate use of static_cast).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,967
Members
47,520
Latest member
KrisMacono

Latest Threads

Top