[英]malloc a char pointer member of a struct
How can I allocate memory for a char pointer member of a non pointer struct?如何为非指针结构的 char 指针成员分配 memory? Let me explain: Here is a small program:
让我解释一下:这是一个小程序:
typedef struct student {
char *name;
} student;
void main()
{
/* If I declare a normal struct */
student Josef;
/* This line doesn't work */
Josef->name = malloc(20*sizeof(char));
/* But if I declare a pointer to struct student */
student *PJosef;
/* This line works */
PJosef->name = malloc(20*sizeof(char));
}
Could you tell me why?你能告诉我为什么吗? And by the way, I saw in some tutorials, a line that allocates memory for that struct pointer like:
顺便说一句,我在一些教程中看到了为该结构指针分配 memory 的行,例如:
PJosef = malloc(sizeof(student->PJosef)); PJosef = malloc(sizeof(student->PJosef)); // (or should I write "struct" before student, even if I typedef-ed?) Is this line necessary?
//(或者我应该在学生之前写“struct”,即使我 typedef-ed?)这行是必要的吗? The program works without it.
该程序在没有它的情况下工作。
Thanks ahead.提前谢谢。
The second example is invalid.第二个例子无效。 As you do not allocate memory for the struct itself you dereference the dangling pointer and invoke a UB.
由于您没有为结构本身分配 memory ,因此您取消引用悬空指针并调用 UB。
It should be它应该是
student *pJosef = malloc(sizeof(*pJosef));
if(pJosef)
pJosef -> name = malloc(20 * sizeof(pJosef -> name[0])); // here also check if allocation failed.
else { /* error handling */}
Note usage of the objects not types in sizeof
s注意对象的用法不是
sizeof
中的类型
Using the ->
operator in:使用
->
运算符:
student Josef;
Josef->name = malloc(20*sizeof(char));
Will not work because Josef
is not a pointer to a struct
.将不起作用,因为
Josef
不是指向struct
的指针。 The ->
operator can only be used on pointers to type struct
. ->
运算符只能用于指向struct
类型的指针。
Instead you should use the .
相反,您应该使用
.
operator:操作员:
student Josef;
Josef.name = malloc(20*sizeof(char));
Note:笔记:
student *PJosef;
PJosef->name = malloc(20*sizeof(char));
Will not work because PJosef
is a uninitialized pointer and accessing it invokes undefined behaviour.将不起作用,因为
PJosef
是一个未初始化的指针并且访问它会调用未定义的行为。
Instead you must first allocate memory for a struct
:相反,您必须首先为
struct
分配 memory :
student *PJosef = malloc(sizeof(struct student));
if (PJosef == NULL)
{
fprintf(stderr, "malloc failed");
// error procedure
}
PJosef->name = malloc(20*sizeof(char));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.