2

When I use code like this :

typedef struct {
        int x;
        int *pInt;
} tData;

tData *ptData = malloc(sizeof(tData));   

If i understand it right, i allocated memory with size of tData and returned adress to this allocated memory to pointer *ptData.

But what if i used this code :

typedef struct {
        int x;
        int *pInt;
} *tData;

If I want to allocate memory to this struct, do I need a struct name? Because for me, if I allocate like malloc(sizeof(*tData));, it seems to me like I am allocating memory only for the pointer, not for the structure itself. When I want to refer to data in this structure, do I need to use pointer to pointer to a struct?
It confuses me a bit and I couldn't find the answer I am looking for.
Thank you for any explanation!

Umang Loriya
  • 840
  • 8
  • 15
SevO
  • 303
  • 2
  • 11
  • That's why don't typedef pointers!! – Sourav Ghosh Oct 27 '17 at 10:29
  • Some discussion [here](https://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers). Apparently you should only typedef pointers like this "if your code will never dereference the pointer," – Karl Reid Oct 27 '17 at 10:29
  • Closing as dupe, if this does not answer your question, let me know. – Sourav Ghosh Oct 27 '17 at 10:31
  • 1
    It didn't. They discussed there first form of code i posted. I have problem understanding the second one. And i can't avoid it, in this situation.. – SevO Oct 27 '17 at 10:41
  • You can use a struct name as you mentioned, or you can typedef both the struct type and the pointer to struct type like this typedef struct { ... } tData, *ptData; – Stuart Oct 28 '17 at 00:24

1 Answers1

3

This is one of the reason one should avoid creating type-aliases of pointers.

As for how to use it, instead of passing the type to the sizeof operator, use the variable. Like e.g.

typedef struct {
        int x;
        int *pInt;
} *tData;

tData ptData = malloc(sizeof *ptData);  // Allocate memory for one structure
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621