【发布时间】:2016-05-25 11:56:48
【问题描述】:
假设我定义了这个student struct:
struct student {
char *name;
};
typedef struct student Student
现在我有以下功能:
void add_student(const char *student_name) {
// create new student
Student *new_s;
new_s = malloc(sizeof(Student));
strncpy(new_s->name, student_name, sizeof(new_s->name) - 1)
}
我想将 student_name 添加到新学生结构的名称中。但是因为const char 和char 不同,我必须使用strncpy。
我尝试过这种方式,但是出现分段错误,怎么了?
【问题讨论】:
-
你可能想看看
strdup,而不是strncpy。这听起来与您尝试在此处存档的内容非常接近。 -
永远不要使用
strncpy它永远不是适合这项工作的工具。
标签: c struct char constants strncpy