Home > database >  how to modify struct string attribute or update struct with a function
how to modify struct string attribute or update struct with a function

Time:03-21

My final goal is to initialize X.fmt with sprintf. My first solution is only to modify the fmt attribute but it didn't worked. Then I set the parameter to struct student_t &X in order to update the struct but it didn't worked either.

Here is my first solution:

char* fmt_str ( struct student_t X )
{
  char *buf;
  sprintf( buf, "%s|%s|%.2f",
           X.id,
           X.name,
           X.gpa );
  return (buf);
}

I need help to find the correct solution to modify the fmt attribute. But a solution that update the struct is also accepted.

CodePudding user response:

char *buf;
sprintf( buf, format, ...);

sprintf requires a pointer to a buffer where the resulting C-string is stored. That buffer should be large enough to contain the resulting string.

You can change the signature of the method to accept a buffer to use such as:

char* fmt_str(struct student_t X, char* buf) {
    sprintf(buf, "%s|%s|%.2f", X.id, X.name, X.gpa);
    return buf;
}

Or judging by your comment

My final goal is to initialize X.fmt

You can pass X by-reference (as a pointer instead of a struct) and modify it's .fmt directly. This is of course assuming the resulting char[] is large enough for the string your writing to it.

struct student_t {
    const char* id;
    const char* name;
    const float gpa;
    char fmt[1024];
};

char* fmt_str(struct student_t* X) {
    sprintf(X->fmt, "%s|%s|%.2f", X->id, X->name, X->gpa);
    return X->fmt;
}
  • Related