2

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};
Pat. ANDRIA
  • 2,330
  • 1
  • 13
  • 27
astro
  • 31
  • 5

3 Answers3

3

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;
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
3

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;
}
Pat. ANDRIA
  • 2,330
  • 1
  • 13
  • 27
1

You can use a pointer to a compound literal:

struct NODE{
   int x;
   int y;
}


struct NODE *nodePtr = &(struct NODE) {
    .x = 20,
    .y = 10
};
  • Notice that compund literals were introduced in C99.
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
RafsanJany
  • 355
  • 1
  • 10
  • If this is used inside a function, the lifetime of the compound literal ends the moment execution of its associated block ends. Initializing a pointer this way should never be taught to students without cautioning them. – Eric Postpischil Feb 24 '21 at 22:13
  • @EricPostpischil Thanks for the information. It would be helpful when some one will use it. – RafsanJany Feb 25 '21 at 04:21