Leon Breedt wrote:

> can anyone tell me why this function works:
> 
> int fopenfile(FILE **fp, char *fname)
> {
>   *fp = fopen(fname, "r+");
>   if (!*fp) 
>        *fp = fopen(fname, "w+");  /* create if not found */
>   
>   return 0;
> }

This will only work if `fp' points to writable memory. If it points to
something other than a variable which exists for this purpose, you may
be overwriting something important, causing your program to crash.

> but this one doesnt:
> 
> int fopenfile(FILE *fp, char *fname)
> {
>   fp = fopen(fname, "r+");
>   if (!fp) 
>       fp = fopen(fname, "w+");  /* create if not found */
>   
>   return 0;
> }

This will work, but it is ignoring the value of `fp' which is passed
in, and you can't get at the file handle from outside the function, so
it isn't of much use.

> any operations i try to do with the file if i opened it with the
> second function, cause a segfault, but if i used the first function,
> i can read/write to the file no problems.
> 
> to me it seems then that the second function is not modifying 'fp' at
> all,

Nope.

> but why not?

Because that's the way that C works. Parameters are passed by value,
not by reference.

        void foo(int x)
        {
                x++;
        }

        void bar(void)
        {
                int n = 0;
                printf("n = %d\n", n);
                foo(n);
                printf("n = %d\n", n);
        }

> is it possible that the fp is only passed by
> value if its declared as FILE *fp?

Parameters are *always* passed by value.

> excuse me if this question is elementary,

It is.

> but i'm a convert from pascal :).

Pascal does exactly the same, unless you use the `var' keyword. E.g.

        procedure foo(var x:integer);
        begin
                x := x + 1
        end

In C, you have to pass a pointer to the variable. e.g.

        void foo2(int *x)
        {
                (*x)++;
        }

        void bar(void)
        {
                int n = 0;
                printf("n = %d\n", n);
                foo2(&n);               /* pass a pointer to `n' */
                printf("n = %d\n", n);
        }

-- 
Glynn Clements <[EMAIL PROTECTED]>

Reply via email to