Mail Archives: djgpp/1999/10/25/17:37:54
Kieran Farrell wrote:
>
> Ack Sorry guys, first rule in asking questions on newsgroups. Never
> assume people know what you're asking *8)
>
> I made a simple question long winded. In short I'm asking how do I
> pass a pointer by refference. Examples for this are opening files, and
> adding nodes to linked lists. the later is what I'm trying to achieve.
> However heres the file example, it might make more sense.
>
> int main(void)
> {
> FILE *fp;
>
> OpenFile(fp);
> return 0;
> }
>
> void OpenFile(FILE *fp)
> {
> fp = fopen('a:\\yadayad.txt", "wb");
> return;
> }
>
> The above wont work, cause whatever pointer is assigned to fp is lost
> when the OpenFile procedure is finished.
You pass a pointer by reference the same as you pass any other type by
reference: by passing a pointer to it.
int main(void)
{
FILE *fp;
OpenFile(&fp);
return 0;
}
void OpenFile(FILE **fp)
{
*fp = fopen('a:\\yadayad.txt", "wb");
return;
}
However...
> OK I'll try showing my quick fix again, hopefully it makes more sense
> and should compile this time.
>
> int main(void)
> {
> FILE *fp;
>
> fp = OpenFile(fp);
> return;
> }
>
> FILE *OpenFile(FILE *fp)
> {
> fp = fopen('a:\\yadayad.txt", "wb");
> return fp;
> }
This is a much cleaner design. It's IMHO preferable to avoid having
functions modify their arguments when possible.
Actually, in this case, passing fp to OpenFile is unnecessary, since you
never use it. It could be:
FILE *OpenFile(void)
{
FILE *fp;
fp = fopen(etc, etc);
return fp;
}
--
Nate Eldredge
neldredge AT hmc DOT edu
- Raw text -