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 char
和char
不同,我必须使用strncpy
.
我以这种方式尝试过,但是出现分段错误,怎么了?
您只为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)
归档时间: |
|
查看次数: |
1603 次 |
最近记录: |