about pointer conversion

H

hpsoar

int *pi;
int **ppi;
pi = (int*)malloc(sizeof(int));
ppi = (int**)pi;
can anyone tell me, how the code above passed compilation? and I saw
another example(http://www.parashift.com/c++-faq-lite/
dtors.html#faq-11.14):
void* ans = pool.alloc(nbytes + 4); // overallocate by 4 bytes
*(Pool**)ans = &pool;
thank you.
 
I

Ian Collins

hpsoar said:
int *pi;
int **ppi;
pi = (int*)malloc(sizeof(int));
ppi = (int**)pi;
can anyone tell me, how the code above passed compilation?

Because is contrails awful C style casts, which suppress the compiler's
better judgement.
and I saw
another example(http://www.parashift.com/c++-faq-lite/
dtors.html#faq-11.14):
void* ans = pool.alloc(nbytes + 4); // overallocate by 4 bytes
*(Pool**)ans = &pool;

Same again! That could be written as

void* ans = pool.alloc(nbytes + 4); // overallocate by 4 bytes
Pool** p = (Pool**)ans;
*p = &pool;
 
W

WANG Cong

hpsoar said:
int *pi;
int **ppi;
pi = (int*)malloc(sizeof(int));
ppi = (int**)pi;
can anyone tell me, how the code above passed compilation? and I saw

You used a casting in the last line, that means you were telling the
compiler that you understand what happened there and do that on purpose.
It's you, not the compiler, who will be responsible to make sure it is
correct.

Probably the right code should be:

ppi = π

according their names...
another example(http://www.parashift.com/c++-faq-lite/
dtors.html#faq-11.14):
void* ans = pool.alloc(nbytes + 4); // overallocate by 4 bytes
*(Pool**)ans = &pool;

You should avoid using the C-style casting in your C++ code.
 

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
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top