user2735868
user2735868

Reputation: 83

Why accessing fields of struct through a typedef-ed pointer does not work?

I have these declarations:

typedef struct egObject {
    int  magicnumber;
} egObject;
typedef struct egObject* ego;

ego e;
//printf("%d",e->magicnumber);

I want to get the magicnumber out of e, but e->magicnumber doesn't work. What's the right way of doing this?

Upvotes: 0

Views: 625

Answers (3)

Mahonri Moriancumer
Mahonri Moriancumer

Reputation: 6003

Here is an example of how to print the magicnumber element of both an egObject, or ego (a pointer to an egObject):

#include <stdio.h>
typedef struct egObject {
    int  magicnumber;
} egObject;
typedef struct egObject* ego;

int main ()
   {
   egObject eo =
      {
      .magicnumber = 42
      };

   ego e = &eo;

   printf("eo.magicnumber = %d\n",eo.magicnumber);
   printf("e->magicnumber = %d\n",e->magicnumber);

   return 0;
   }

Results:

> ./test
eo.magicnumber = 42
e->magicnumber = 42
>

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

When you declare a struct, you allocate memory for a struct:

egObject e;

When you declare a pointer to a struct, typedef-ed or not, you allocate space to the pointer, but not for the struct. In order to access a field of a struct you need to allocate that struct first. A particular way in which you do it does not matter - you could allocate it statically, dynamically, or in the automated storage, but you must allocate some memory for it:

ego e = malloc(sizeof(*e));

That is enough to access the field for writing. Reading that field requires initialization, because malloc-ed block contains uninitialized bytes in the area allocated to magicnumber:

e->magicnumber = 123;

Now you can print magicnumber the way that your code did:

printf("%d",e->magicnumber);

Note: if you choose dynamic allocation with malloc, you need to free the object once you are done using it:

free(e); // Avoid memory leaks

Upvotes: 5

turbulencetoo
turbulencetoo

Reputation: 3691

The line ego e; is essentially the same as struct egObject *e. The issue there is that this line only allocates memory for a pointer to struct it never allocates memory for the struct. Because you never actually make a struct, there is no reason to be able to access one of its members.

To do this correctly you could:

struct egObject obj; //allocate one struct
ego e = &obj;        //allocate one pointer to struct and 
                     // fill that pointer with the address of your struct

//e now 'points' to 'obj' 
//so you can use e->magicnumber

Upvotes: 3

Related Questions