UFC Insider
UFC Insider

Reputation: 838

Memory allocation to a struct with a pointer

In foo.h I have:

struct Foo_st {
    int a;
    MyObj obj1, obj2;
};

typedef struct Foo_st* Foo;

And inside foo.c I want to allocate space for my struct, so I try:

Foo foo1 = (Foo) malloc(sizeof(Foo_st));

But I get an error -

'Foo_st' undeclared (first use in this function)


What am I doing wrong?

Upvotes: 3

Views: 83

Answers (3)

chqrlie
chqrlie

Reputation: 144695

Your code fails in C because the type Foo_st is not defined (contrary to C++).

You can correct this in 3 different ways:

  • Add the struct keyword:

    Foo foo1 = malloc(sizeof(struct Foo_st));
    
  • Define the type Foo_st:

    typedef struct Foo_st {
        int a;
        MyObj obj1, obj2;
    } Foo_st;
    typedef struct Foo_st *Foo;
    
    Foo foo1 = malloc(sizeof(Foo_st));
    
  • Use the type of the destination pointer (a safer option IMHO):

    Foo foo1 = malloc(sizeof(*foo1));
    

Note that it is considered bad style to hide pointers behind typedefs. It tends to be error prone and produces non idiomatic code confusing for both the readers and the programmer.

Upvotes: 0

4pie0
4pie0

Reputation: 29724

You must typedef struct to be able to use it without struct keyword, just as you did with typedefed pointer:

typedef struct {
    int a;
    MyObj obj1, obj2;
} Foo_st;
typedef Foo_st* Foo;
// note: ^^^^^^^^ there is no struct keyword as Foo_st is already
// a typedef for struct, i.e. struct Foo_st


Foo foo1 = malloc(sizeof(Foo_st));

Note: There is no need to cast malloc in C.

Upvotes: 1

davmac
davmac

Reputation: 20631

In C, struct names must be preceded by struct. You want:

Foo foo1 = malloc(sizeof(struct Foo_st));

Alternatively, replace your struct Foo_st declaration with a typedef:

typedef struct {
    int a;
    MyObj obj1, obj2;
} Foo_st;

This defines Foo_st as an alias to an anonymous struct type. Your original allocation statement will then work.

Upvotes: 2

Related Questions