我在这里有一个简单的练习。我在结构中创建了以下结构。C:
struct student {
char *first;
char *last;
string name;
int id;
double GPA;
};
我需要提出以下功能并在同一文件中定义它:
setName(char* name[size])
getName()
setID()
setGPA(double GPA)
getGPA()
,如果尚未初始化结构,我不明白我应该如何创建固定器和获取器。我猜想我使用指针,但我不确定如何在c。
中这样做,然后我应该在标题文件中声明/列出所有这些功能,我也很困惑。
您需要将POITNER传递给每个setter/getter函数,例如
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()'n"), __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()'n"), __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;
}
您可以使用此功能
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: %sn", first_name);
/* work with `student', and when you finish */
free(student.first);
/* and all other `malloc'ed stuff */
好处是,您可以向库用户隐藏结构定义,并防止他们滥用Structre,例如设置无效的值和其他内容。