J
JD
Hi guys
What if I need to return two values from a function. What's the best way
to do it?
Function is to load a text file into memory like so:
-----8<-----
char *LoadFile(char *infile)
{
FILE *f;
int c;
int bytesread, bytestotal;
char *buf, *p, *tmp;
if ((f = fopen(infile, "r")) == NULL) {
printf("Can't open \"%s\" for reading\n", infile);
return NULL; /* NULL means failure to calling function */
}
bytesread = 0;
bytestotal = 0;
buf = NULL;
while ((c = fgetc(f)) != EOF) {
if (bytestotal - bytesread == 0) {
bytestotal += 1024;
tmp = realloc(buf, bytestotal);
if (tmp == NULL) {
printf("*** Out of memory ***\n");
return NULL;
}
buf = tmp;
p = buf + bytesread;
}
*p++ = c;
bytesread++;
}
*p = '\0'; /* terminate string...could this be out of bounds in
certain situations? */
fclose(f);
return buf;
}
----->8-----
I need to return the pointer to the memory as well as "bytestotal" so I
can allocate another block of memory for working with the data (copying
it back and forth to do operations on it etc.) It seems inefficient to
call the function twice so I have two blocks of memory.
I'm aware of some possibilities: use "call by reference", return a
struct, use a global variable. I'm just not sure which to choose and why.
Thanks!
What if I need to return two values from a function. What's the best way
to do it?
Function is to load a text file into memory like so:
-----8<-----
char *LoadFile(char *infile)
{
FILE *f;
int c;
int bytesread, bytestotal;
char *buf, *p, *tmp;
if ((f = fopen(infile, "r")) == NULL) {
printf("Can't open \"%s\" for reading\n", infile);
return NULL; /* NULL means failure to calling function */
}
bytesread = 0;
bytestotal = 0;
buf = NULL;
while ((c = fgetc(f)) != EOF) {
if (bytestotal - bytesread == 0) {
bytestotal += 1024;
tmp = realloc(buf, bytestotal);
if (tmp == NULL) {
printf("*** Out of memory ***\n");
return NULL;
}
buf = tmp;
p = buf + bytesread;
}
*p++ = c;
bytesread++;
}
*p = '\0'; /* terminate string...could this be out of bounds in
certain situations? */
fclose(f);
return buf;
}
----->8-----
I need to return the pointer to the memory as well as "bytestotal" so I
can allocate another block of memory for working with the data (copying
it back and forth to do operations on it etc.) It seems inefficient to
call the function twice so I have two blocks of memory.
I'm aware of some possibilities: use "call by reference", return a
struct, use a global variable. I'm just not sure which to choose and why.
Thanks!