你需要傳遞一個poitner的結構,每個二傳手/ 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: %s\n", first_name);
/* work with `student', and when you finish */
free(student.first);
/* and all other `malloc'ed stuff */
的好處是,你可以隱藏庫用戶的結構定義,並防止他們濫用結構,如設置無效值和其他東西。
偉大的職位謝謝,大大澄清了事情。我仍然對頭文件中應該做什麼感到困惑,因爲它涉及到使用它的功能。任何幫助? – bfalco
搜索谷歌關於轉發聲明,只是提供一個'struct'和每個函數的原型,還有一些關於該主題的其他文章,其中之一是我的。 –