N
none
Hello, I was reading some of the FAQ last night and got to this one,
http://c-faq.com/ptrs/genericpp.html . Now i'd just like to make sure
i'm understanding it correctly, so please correct me where i'm wrong.
The code below is just a quick example, and makes assumptions to keep
it simple (i.e malloc never fails).
#include <stdio.h>
#include <stdlib.h>
/* This is wrong since *ptr was not converted */
void foo( void **p )
{
int **ptr = (int**)p;
*ptr = malloc( sizeof(int)*6 );
return;
}
/* This is ok since *p will be implicitly casted to return
pointer-to-int while remaining pointer-to-void */
int* bar( void **p )
{
*p = malloc( sizeof(int)*6 );
return *p;
}
/* This is fine since v is the pointer-to-void from malloc */
void foo2( void *v )
{
int *i = v;
printf("%d\n", *i);
}
int main(void)
{
int *i=NULL;
void *v = i;
foo(&v);
free(v);
i = bar(&v);
*i = 8;
foo2(v);
free(i);
return 0;
}
http://c-faq.com/ptrs/genericpp.html . Now i'd just like to make sure
i'm understanding it correctly, so please correct me where i'm wrong.
The code below is just a quick example, and makes assumptions to keep
it simple (i.e malloc never fails).
#include <stdio.h>
#include <stdlib.h>
/* This is wrong since *ptr was not converted */
void foo( void **p )
{
int **ptr = (int**)p;
*ptr = malloc( sizeof(int)*6 );
return;
}
/* This is ok since *p will be implicitly casted to return
pointer-to-int while remaining pointer-to-void */
int* bar( void **p )
{
*p = malloc( sizeof(int)*6 );
return *p;
}
/* This is fine since v is the pointer-to-void from malloc */
void foo2( void *v )
{
int *i = v;
printf("%d\n", *i);
}
int main(void)
{
int *i=NULL;
void *v = i;
foo(&v);
free(v);
i = bar(&v);
*i = 8;
foo2(v);
free(i);
return 0;
}