newbie said:
Can someone please give me some tips?
I have a function f(). In function f() I allocate memory for a char
array. Now the memory I allocate in f() must be assigned to a char*
outside of f() so how would I pass in a char* and assign it the address
of the allocated memory, example:
void f(char* p)
{
char* a=(char* )malloc(10);
// do some error checking;
return(0);
}
Not like that!
Firstly, drop your cast on malloc. It's not required, and can conceal a bug.
If your compiler seems to be telling you that it /is/ required, check that
you've got <stdlib.hincluded. Chances are you haven't. Include it, and
the warning message will go away. If it doesn't, then you're accidentally
using a C++ compiler instead of a C compiler.
Secondly, let's answer your question. Here's the simple way:
#include <stdlib.h>
char *f(void)
{
return malloc(10);
}
int main(void)
{
char *b = f();
if(b != NULL)
{
/* use b for whatever you wanted 10 bytes of memory for, and then... */
free(b);
}
return 0;
}
And here's the less simple way:
#include <stdlib.h>
void f(char **a) /* note the >>>two<<< stars */
{
*a = malloc(10);
}
int main(void)
{
char *b = NULL;
f(&b);
if(b != NULL)
{
/* use b for whatever you wanted 10 bytes of memory for, and then... */
free(b);
}
return 0;
}
<snip>
How would I call f() so that afterwards b, in main(), points to the
memory allocated in function f()? Do I need to change the
declaration/definition of f() to something like:
void f(char** p)...
Yes. See above.
Or other and how would I call f()?
Again, see above.
Please note this is not any
howework or such I am purely learning C in my spare time.
In this case, it wouldn't have mattered if it were your homework, since it
was clear from your question that you were trying to understand, and had
made a fair effort on your own account. This newsgroup is not against
helping with homework. It's against laziness and dishonesty. You failed to
meet the qualifying criteria for being an Enemy of comp.lang.c. ;-)
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)