[英]How To Initialize a C Struct using a Struct Pointer and Designated Initialization
How can I use struct pointers with designated initialization?如何使用具有指定初始化的结构指针? For example, I know how to init the struct using the dot operator and designated initialization like:例如,我知道如何使用点运算符和指定的初始化来初始化结构,例如:
person per = { .x = 10,.y = 10 };
But If I want to do it with struct pointer?但是如果我想用结构指针来做呢?
I made this but it didn't work:我做了这个,但没有用:
pper = (pperson*){10,5};
If pper
is a person *
that points to allocated memory, you can assign *pper
a value using a compound literal, such as either of:如果pper
是指向分配的 memory 的person *
,您可以使用复合文字为*pper
pper 分配一个值,例如:
*pper = (person) { 10, 5 };
*pper = (person) { .x = 10, .y = 5 };
If it does not already point to allocated memory, you must allocate memory for it, after which you can assign a value:如果它尚未指向已分配的 memory,则必须为其分配 memory,然后您可以分配一个值:
pper = malloc(sizeof *pper);
if (!pper)
{
fputs("Error, unable to allocate memory.\n", stderr);
exit(EXIT_FAILURE);
}
*pper = (person) { 10, 5 };
or you can set it to point to an existing object:或者您可以将其设置为指向现有的 object:
pper = &SomeExistingPerson;
A compound literal looks like aa cast of a brace-enclosed initializer list.复合文字看起来像大括号括起来的初始化列表的强制转换。 Its value is an object of the type specified in the cast, containing the elements specified in the initializer.它的值是类型转换中指定的 object,包含初始化程序中指定的元素。 Here is a reference .这是一个参考。
For a struct pperson
, for instance, it would look like the following:例如,对于struct pperson
,它看起来如下所示:
#include <stdio.h>
#include <malloc.h>
struct pperson
{
int x, y;
};
int main()
{
// p2 is a pointer to structure pperson.
// you need to allocate it in order to initialize it
struct pperson *p2;
p2 = (struct pperson*) malloc( sizeof(struct pperson));
*p2 = (struct pperson) { 1, 2 };
printf("%d %d\n", p2->x, p2->y);
// you may as well intiialize it from a struct which is not a pointer
struct pperson p3 = {5,6} ;
struct pperson *p4 = &p3;
printf("%d %d\n", p4->x, p4->y);
free(p2);
return 0;
}
You can use a pointer to a compound literal:您可以使用指向复合文字的指针:
struct NODE{
int x;
int y;
}
struct NODE *nodePtr = &(struct NODE) {
.x = 20,
.y = 10
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.