0

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.

1 Answer 1

1
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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.