Giox said:
Hello everybody I want to create a routine that mimic the fread
behavior operating on char array.
I wrote
size_t fread_char(void* buf, size_t sz, size_t n, char* string_source)
{
memcpy(buf, string_source, sz*n);
string_source += n*sz;
return n;
}
When I leave the routine the string_source doesn't change its value, it
seems that the operation string_source += n*sz; has not been performed
C passes parameters by value, so fread_char()'s "string_source" variable
contains the _value_ of the parameter passed to it. (Basically, in this
case, it's a copy of the pointer.)
When fread_char() modifies string_source, it modifies its own local copy,
not the caller's original variable.
One way to handle this is to pass the address of the char*, rather than
the char* itself:
size_t fread_char(void* buf, size_t sz, size_t n, char** string_source)
{
memcpy(buf, *string_source, sz*n);
*string_source += n*sz;
return n;
}
Another method would be to define a struct to correspond to the FILE
struct used by fread()/etc. and pass a pointer to the struct rather
than the buffer itself. (The struct would contain, at a minimum, the
same thing as "string_source" above. However, you might want to have
both an "original" string pointer and a "current" pointer, plus a
"length", should you want to be able to simulate fseek and the like.)
--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody |
www.hvcomputer.com | |
| kenbrody/at\spamcop.net |
www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:
[email protected]>