1

It might be a dumb question, but I've searched and couldn't find an answer.

For example

FILE *fp = fopen (argv\[1\], "w");
...
fputs (input, fp)[1];

The fp doesn't have a * in front of it. I thought you needed the * in order to access the data. This way are we not only using the address of the text? How does that work?

CS50 video on File I/O

0

If you executed

man fputs

in the terminal, you would find that fputs takes a char * and a FILE * not a FILE. You can still access the data through a pointer. In fact, this is what fputs is likely to be doing underneath the hood (i.e., accessing the data stored in the struct pointed to by the FILE * in order to update it).

As a short example

// define the struct
struct foo
{
    int bar;
};

// define a type synonym
type struct foo foo;

// define a function that takes a foo *
void baz(foo *fPtr)
{
    if (fPtr)
        // access the member named bar through fPtr
        printf("%d\n", fPtr->bar);
}

/* allocates memory for a foo, initializes the member bar to 0
 * and returns a pointer to the struct */
foo *initFoo(void)
{
    foo *p = malloc(sizeof (foo));
    p->bar = 0;
    return p;
}

// ...

foo *p = initFoo();
baz(p); // NOTICE that I passed a foo * and still can access bar

Output:

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .