gpt4 book ai didi

c - strncpy 只复制部分字符串

转载 作者:太空宇宙 更新时间:2023-11-04 01:04:05 24 4
gpt4 key购买 nike

假设我有这样的结构

typedef struct _student {
int studentID;
char name[30];
char class[10];
char department[10];
} Student;

下面的函数创建了 Student 类型的新变量:

Student *new_student(int id, char *name, char *class, char *dept) {
Student *s = (Student *)malloc(sizeof(Student *));

s->studentID = id;
strncpy(s->name, name, sizeof(s->name) - 1);
s->name[sizeof(s->name) - 1] = '\0';
strncpy(s->class, class, sizeof(s->class) - 1);
s->class[sizeof(s->class) - 1] = '\0';
strncpy(s->department, dept, sizeof(s->department) - 1);
s->department[sizeof(s->department) - 1] = '\0';
return s;
}

void display_student(Student *s) {
printf("Student: %d | %s | %s | %s\n", s->studentID, s->name, s->class, s->department);
}

为了测试我的代码,我只是在 main() 中写了一些简单的东西

int main() {

Student *s1 = new_student(20111201, "Lurther King Anders Something", "ICT-56", "SoICT");
Student *s2 = new_student(20111202, "Harry Potter", "ICT-56", "SoICT");
Student *s3 = new_student(20111203, "Hermione Granger", "ICT-56", "SoICT");
Student *s4 = new_student(20111204, "Ron Weasley", "ICT-56", "SoICT");
display_student(s1);
display_student(s2);
display_student(s3);
display_student(s4);

return 0;
}

然而,结果对我来说是出乎意料和奇怪的:

Erro

有人可以为我解释为什么奇怪的结果吗!我认为我做事的方式是正确的,我安全地使用了 strncpy,但我不理解输出。

最佳答案

这个

 ... malloc(sizeof(Student *));

分配

sizeof(Student *)

字节。通常为 4 或 8,因为 Student * 是指针类型。

你可能想要

     ... malloc(sizeof(Student));

甚至更好:

Student * s = malloc(sizeof(*s));

甚至没有无用的括号:

Student * s = malloc(sizeof *s); /* sizeof is an operator, not a function. */

阅读 malloc(sizeof *s) 为:“分配与 s 所指向的一样多的字节。

关于c - strncpy 只复制部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28126163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com