Home > OS >  fprintf() to a csv file in C by using pointer
fprintf() to a csv file in C by using pointer

Time:10-15

I have a structure defined like this

typedef struct{
    int id;
    char* name;
    float percentage;
}student_t;

And there is a function that is to print struct's member in this format

"id, name, percentage\n"

But the function takes in void* val_ref //struct ptr, void* fp How do I make it work? The function looks like this (paramters are given cannot be modified)

void printStudentInfo(void* val_ref, void* fp)
{
    if (val_ref != NULL)
    {
        fprintf(fp, "%d,%s,%.2f", val_ref->id, val_ref->name, val_ref->percentage);
    }
}

But I can't compile, it says warning: deferencing void* pointer error: request for memeber "id" in something not a struct or union error: request for memeber "name" in something not a struct or union error: request for memeber "percentage" in something not a struct or union

Do I have to do type cast for parameter val_ref?

CodePudding user response:

fprintf(fp, "%d,%s,%.2f", val_ref->id, val_ref->name, val_ref->percentage); Over here, you need to cast val_ref to the type of pointer it actually is: (student_t *)val_ref and then fetch a member of the struct for e.g. ((student_t*)val_ref)->id.

When you have a void*, your program does not know the actual data type you are pointing to. Hence, it is illegal to try to fetch a member. Upon using a cast, you are explicitly saying that val_ref points to a student_t and you know what you are doing when you ask for a specific member.

However, there is no need to cast fp because the function fprintf has the first argument as FILE * in it's signature:

int fprintf(FILE *stream, const char *format, ...);

So, even if you pass a void * as the first parameter, the local variable stream is defined as a FILE * and that's what the function works with.

  • Related