void setmem(char *pt)
{
pt = (char *) malloc (sizeof(char)*6);
}
int main()
{
char *pt = NULL;
setmem(pt);
strcpy(pt, "Hello");
printf("\nmy pt=%s", pt);
}
Need help on passing malloc pointer
Hello, I'm stuck.[help] I play around with pointers and malloc to revise my C, but then i got stuck. Could anyone save me on this? Anyone know how to malloc a block of memory in a function, like the one below, without "return"-ing a pointer?[crying]
Thank you~
[grin]
You've created a mem leak there, since you won't modify the passed in pointer but merly a stackbased copy of it.
What I'm guessing that you want is a pointer pointer like so
and then you could do:
hope that was of assistance.
What I'm guessing that you want is a pointer pointer like so
void setmem(char **pt){ *pt = malloc( sizeof(char) * 6);}
and then you could do:
int main(){ char *pt = NULL; printf( "pt berfore call:%p\n", pt); setmem( &pt); printf( "pt after call:%p\n", pt);//don't forget to free the memory when you're done free( pt);}
hope that was of assistance.
Beaten to it...
Make a pointer-to-pointer and your problem is solved. However, you need to dereference it first in order to malloc it.
Toolmaker
void setmem(char **pt){ *pt = (char *) malloc (sizeof(char)*6);}int main(){ char *pt = NULL; setmem(&pt); strcpy(pt, "Hello"); printf("\nmy pt=%s", pt);}
Make a pointer-to-pointer and your problem is solved. However, you need to dereference it first in order to malloc it.
Toolmaker
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement