Reputation: 51
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};
Upvotes: 4
Views: 1785
Reputation: 2412
A compound literal looks like a a 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. Here is a reference.
For a struct pperson
, for instance, it would look like the following:
#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;
}
Upvotes: 4
Reputation: 355
You can use a pointer to a compound literal:
struct NODE{
int x;
int y;
}
struct NODE *nodePtr = &(struct NODE) {
.x = 20,
.y = 10
};
Upvotes: 1
Reputation: 222753
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 = (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:
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:
pper = &SomeExistingPerson;
Upvotes: 4