Hi I have the following structure in the file structure.c #include struct studen
ID: 657355 • Letter: H
Question
Hi I have the following structure in the file structure.c
#include
struct student{
char *first;
char *last;
string name;
int id;
double GPA;
}
I am new to C progamming and i dont understand how I am suppose to define the following functions without instantiating the structure first
I need to define the following functions in the same c file and then enlist/declare them in the header file aswell. I am very confused as how to define these functions and how to enlist them in the header file. If someone could provide 1 example for one set method and one get method i will be very grateful. -
setName ( char* name[size])
getName()
setID(int)
getID()
setGPA(double GPA)
getGPA()
Thank you,
Explanation / Answer
You need to pass a poitner to the structure to each setter/getter function, for example
void
student_set_first_name(struct student *student, const char *const name)
{
size_t length;
if ((student == NULL) || (name == NULL))
{
fprintf(stderr, "Invalid parameters for `%s()' "), __FUNCTION__);
return;
}
/* In case we are overwriting the field, free it before
* if it's NULL, nothing will happen. You should try to
* always initialize the structure fields, to prevent
* undefined behavior.
*/
free(student->first);
length = strlen(name);
student->first = malloc(1 + length);
if (student->name == NULL)
{
fprintf(stderr, "Memory allocation error in `%s()' "), __FUNCTION__);
return;
}
memcpy(student->first, name, 1 + length);
}
const char *
student_get_first_name(struct student *student)
{
if (student == NULL)
return NULL;
return student->first;
}
And you could use the function like this
struct student student;
const char *first_name;
memset(&student, 0, sizeof(student));
student_set_first_name(&student, "My Name");
first_name = student_get_first_name(&student);
if (first_name != NULL)
fprintf(stdout, "First Name: %s ", first_name);
/* work with `student', and when you finish */
free(student.first);
/* and all other `malloc'ed stuff */
The good thing is that you could hide the structure definition from the library user and prevent them from misusing the structre, like setting invalid values and other things.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.