I understand that a char buffer is passed into a function when it has to
return a string. What I am not very clear about is why does it need a
char** and not a char* directly.
If memory is allocated for the buffer in either case using malloc,
shouldn't it work the same? A short working example is pasted below with
two functions, one of which takes a char** and the other char*.
Appreciate the help.
#include <stdio.h>
#include <stdlib.h>
void getname(char **);
void getname2(char *);
int main(void)
{
char *c = NULL;
char *d = NULL;
getname(&c);
printf("char - %d\t\t%d\n", *c, sizeof *c);
printf("char * - %d\t%d\n", c, sizeof c);
printf("char ** - %d\t%d\n", &c, sizeof &c);
printf("---\n");
getname2(d);
printf("char - %d\t\t\n", *d); // Crashes here
printf("char * - %d\t%d\n", d, sizeof d);
printf("char ** - %d\t%d\n", &d, sizeof &d);
}
void getname(char **c)
{
char s[] = "Oranges and Lemons sold for a penny";
*c = malloc(10 * sizeof **c);
sprintf(*c, "%s", s);
}
void getname2(char *d)
{
char s[] = "Oranges and Lemons sold for a penny";
d = malloc(10 * sizeof *d);
sprintf(d, "%s", s);
printf("char - %d\t\t%d\n", *d, sizeof *d);
}
Regards,
Pranav Negandhi
www.pranavnegandhi.com


|