![](/img/trans.png)
[英]How To Initialize a C Struct using a Struct Pointer and Designated Initialization
[英]How to initialize a struct using pointer?
我是C的新手,我在练习时遇到了这个问题。
结构:
typedef struct {
char name[20];
int score[3];
int no;
} Student;
初始化:
Student *pStudent;
strcpy(pStudent->name,"Kven");
pStudent->score[0]=1;
pStudent->score[1]=2;
pStudent->score[2]=3;
pStudent->no=1;
如果“pStudent”不是指针,我可以把它弄好。 但如果它是一个指针,我总会得到一个“错误访问”错误。 如果我必须使用指针,如何解决? 谢谢。
类型指针的变量将地址存储在另一个变量的内存中(它指向另一个变量)。
您的变量pStudent
未初始化。 它没有任何意义。 实际上,它包含一些垃圾值,大多数情况下,它是不允许程序写入的内存区域的地址。 这就是为什么当你尝试在那里写( strcpy()
的调用)时,操作系统会把你的程序打到它的“hand”上,然后用你提到的错误信息终止它。
指针的一种用法是指向静态分配的某个变量(在程序中定义):
Student s, *pStudent = &s;
此示例声明了Student
类型的变量s
和指向它的变量pStudent
。 请注意,它与初始化&s
是地址s
。 现在,您的代码使用pStudent
初始化s
的字段。
指针的另一个用法是在运行时动态分配内存:
Student *pStudent;
pStudent = malloc(sizeof(Student));
在这种情况下, pStudent
使用通过调用malloc()
在运行时创建的类型为Student
的新变量的地址初始化(它没有名称malloc()
。 malloc()
分配一块内存(指定大小)并返回其地址。
当您不需要它时,您必须释放malloc()
分配的malloc()
(使用free()
)以便重用:
free(pStudent);
在此调用之后,变量pStudent
的值不会更改,它仍指向相同的地址,但它无效并使用它会产生未定义的行为。 在pStudent
使用之前,您必须将另一个Student
结构的地址放在pStudent
(使用此处介绍的两种方法之一)。
Student *pStudent;
应该
Student *pStudent = malloc(sizeof(Student));
在使用它完成数据写入之前为指针分配内存
free(pStudent);
Student *pStudent;
创建一个Student*
类型的指针。 该指针未初始化并指向某个“随机”位置。 使用stdlib.h
malloc
(或calloc
)为它分配内存:
pStudent = malloc(sizeof(Student));
然后在使用后将其释放:
free(pStudent);
你没有分配任何内存,你只需要分配一个指针。 你需要学习指针及其工作原理。
修复这样的代码:
Student student;
strcpy(student.name,"Kven");
student.score[0]=1;
student.score[1]=2;
student.score[2]=3;
student.no=1;
或者,您可以动态分配内存。 但在这种情况下它没有任何意义 (但我打赌至少有3个人会发布答案,告诉你这样做......)。 另外,在进行动态分配之前,您确实需要学习指针。
Student *pStudent = calloc(1, sizeof(Student);
if(pStudent == NULL)
{
// error handling
}
strcpy(pStudent->name,"Kven");
pStudent->score[0]=1;
pStudent->score[1]=2;
pStudent->score[2]=3;
pStudent->no=1;
...
free(pStudent);
您需要先为结构分配内存。
你可以用以下内容分配内存
Student *pStudent = malloc(sizeof(Student));
然后你必须在最后释放它
free(pStudent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.