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!

5
  • That's why don't typedef pointers!! Commented Oct 27, 2017 at 10:29
  • Some discussion here. Apparently you should only typedef pointers like this "if your code will never dereference the pointer," Commented Oct 27, 2017 at 10:29
  • Closing as dupe, if this does not answer your question, let me know. Commented Oct 27, 2017 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.. Commented Oct 27, 2017 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; Commented Oct 28, 2017 at 0:24

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

And may i ask, if i would change it to typedef struct data {...} *tData;, would struct data *pData; mean the same as tData pData; ?
@SevO Yes it would.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.