在结构上使用 strncpy

bak*_*tle 2 c struct constants char strncpy

假设我有这个student struct定义:

struct student {
    char *name;
};
typedef struct student Student
Run Code Online (Sandbox Code Playgroud)

现在我有以下功能:

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)
}
Run Code Online (Sandbox Code Playgroud)

我想将 student_name 添加到新学生结构的名称中。但是因为const charchar不同,我必须使用strncpy.

我以这种方式尝试过,但是出现分段错误,怎么了?

Har*_*ris 5

您只为new_s这一行中的结构分配内存

new_s = malloc(sizeof(Student));
Run Code Online (Sandbox Code Playgroud)

这包括变量char* name,它是一个pointer to a char. 虽然,您还需要此指针将指向的内存。

因此,您需要为name结构内的字符指针分配内存。

// create new student
Student *new_s;
new_s = malloc(sizeof(Student));

new_s->name = malloc(100); //assuming you need to store a string of len 100
Run Code Online (Sandbox Code Playgroud)