【发布时间】:2017-06-06 12:56:41
【问题描述】:
我必须在下面的internal.h中实现这些功能:
#ifndef STUDENT_INTERNAL_H
#define STUDENT_INTERNAL_H
#include "student.h"
/** Allocate memory for a new @ref student object. */
struct student *student_alloc(void);
/*** Initialize an already-allocated @ref student object.
* @returns NULL on failure but does not free the memory
*/
struct student *student_init(struct student *, const char *name, size_t namelen,
struct student_id, student_complete);
#endif /* STUDENT_INTERNAL_H */
这是我到目前为止所拥有的,但我很困惑并且它不起作用:
#include <sys/types.h>
#include "common.h"
#include "student.h"
#include "transcript.h"
#include "internal.h"
/**
* Initialize an already-allocated @ref student object.
* @returns NULL on failure but does not free the memory
*/
struct student *student_init(struct student *student, const char *name, size_t namelen,
struct student_id stud_id, student_complete stud_complete) {
struct student *initialized_student;
name = malloc(sizeof(namelen));
initialized_student = malloc(sizeof (student));
if (student_alloc()) {
initialized_student->s_name = name;
initialized_student->s_id = stud_id;
initialized_student->s_complete = stud_complete;
return initialized_student;
} else {
return 0;
}
}
stud_complete 这是一个函数指针,它在一个不同的头文件 student.h 中声明,例如typedef int (*student_complete)(struct student *);
【问题讨论】:
-
或许学习如何使用调试器是个好主意
-
initialized_student = malloc(sizeof (student));是错误的 -->>initialized_student = malloc(sizeof (struct student));甚至更好:initialized_student = malloc(sizeof *initialized_sudent);和name = malloc(sizeof(namelen));也是错误的。
标签: c memory-management malloc function-pointers dynamic-programming