Sam <sa*@iam.netwri tes:
Hi there. I hope this code is standard C. I think it is. Anyway, I
haven't used C in a Looooooong time and am a little rusty on
pointers. I am wondering why "buff" is a pointer to a pointer instead
of just "*buff". I'm also not really sure about the language of
pointers. Is it correct to say "pointer to a pointer to buff" or
"double pointer to buff" or what? If you can help me with this, you
have my thanks...
REM --- *Code Below* ---
void LoadFileIntoMem ory(const char *name, void **buff, int *length)
{
FILE *fp = fopen(name, "rb");
fseek(fp, 0, SEEK_END);
*length = ftell(fp);
fseek(fp, 0, SEEK_SET);
*buff = malloc(*length) ;
fread(*buff, *length, 1, fp);
fclose(fp);
}
REM --- *End Code* ---
As you probably know, but I'll emphasize it anyway, all function
arguments are passed by value. A parameter is a local variable,
containing (at least initially) a copy of the argument value.
Modifying the parameter object (name, buff, or length in this case)
only modifies this local variable, which ceases to exist when the
function returns.
Consider a call to this function:
void *buff;
int length;
LoadFileIntoMem ory("foo.dat", &buff, &length);
The function passes back two pieces of information to the caller: the
location where it stored the data, and the length of the data.
The location of the data is represented as a void*; the length of the
data is represented as an int. So the caller has to pass in *a
pointer to* a void*, and *a pointer to* an int, so that the function
knows where to store the void* and int values that the caller needs.
Suppose the arguments were just a void* and an int:
void LoadFileIntoMem ory(..., void **buff, int length);
{
length = ftell(fp);
...
buff = malloc(length);
}
Then the values of length and buff would be lost.
As for terminology, "pointer to pointer to void" is fine (it's not a
pointer to pointer to buff; buff *is* the pointer). The term "double
pointer" should be avoided, unless you're talking about a double*
(i.e., a pointer to a floating-point object).
As for the function itself:
There is no error checking, and no mechanism for the function to
report an error to its caller. What if fopen() fails for any of a
variety of reasons? What if fseek() fails because you passed it the
name of the keyboard device? What if malloc fails because you've run
out of memory? Likewise for fread and fclose.
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"