Just a little clarification, please:
If I use malloc, where CHAR_BUFFER_SIZE is previously defined to 256, for example:
Code:
char* name = (char *)malloc(CHAR_BUFFER_SIZE);
I need to free it somewhere using:
If this variable name is a return value, can you explain a bit for me the best way to proceed?
Just for simplicity, if there's a function, for example:
Code:
void test()
{
char* name = (char *)malloc(CHAR_BUFFER_SIZE);
name = getName();
printf("Name = %s", name);
name = reverseName(name);
printf("Name = %s", name);
free(name);
}
Code:
char* getName()
{
char* name = (char *) malloc(CHAR_BUFFER_SIZE);
// ..... whatever code here
return name;
}
Code:
char* reverseName(char* name)
{
char* newName = (char *) malloc(CHAR_BUFFER_SIZE);
// ..... error check here for newName to see if malloc worked
// ..... error check here for name for validity
// ..... code here to reverse the name ...
return newName ;
}
Now in this function I have a char* called name, however -- it calls a function getName which returns a char*.
Is it better to pass it in as a parameter instead? How do I send a char pointer to a function?
The same goes for reverseName(), it would be better written to send in a char pointer as well (the address of), create the newName with the reversed letters, copy it back to the char* name sent in, and free(newName).
If I understand it right... and then I wouldn't have to use:
Code:
name = reverseName(name);
Thanks....