notmydisplayname
notmydisplayname

Reputation: 3

Setting up structs in C - giving strange errors

I have set-up structs like so in a C program:

typedef struct header block_header;

struct header {
    size_t size;
    block_header *next_pointer;
    block_header *prev_pointer;
};

However, when I run any expression like the following:

int myinit()
{
    block_header *p = init_heap_segment(BLOCK_HEAD_SIZE);

// etc etc
}

It gives me several errors for each function that it is declared in:

allocator.c: In function ‘myinit’:
allocator.c:37:38: error: ‘header’ undeclared (first use in this function)
allocator.c:37:38: note: each undeclared identifier is reported only once for each function it appears in
allocator.c: In function ‘function’:
allocator.c:67:2: error: unknown type name ‘header’

What is the problem with the way that it is set-up? How do I make these errors go away?

EDIT: Definition of:

#define BLOCK_HEAD_SIZE (ALIGN(sizeof(header)))

Upvotes: 0

Views: 156

Answers (3)

ButchDean
ButchDean

Reputation: 70

Why not just do:

typedef struct block_header {
    size_t size;
    block_header *next_pointer;
    block_header *prev_pointer;
}header;

and with that you can do:

header *p = init_heap_segment(BLOCK_HEAD_SIZE);

with a new declaration for init_heap_segment() where it returns 'header *' instead of 'struct block_header *'. Just much cleaner.

Upvotes: 0

Sathish
Sathish

Reputation: 3870

In your program, there is no such type called header. But you are using

#define BLOCK_HEAD_SIZE (ALIGN(sizeof(header))) // problem

It should be-

#define BLOCK_HEAD_SIZE (ALIGN(sizeof(struct header)))

or

#define BLOCK_HEAD_SIZE (ALIGN(sizeof(block_header)))

Whenever you are calculating size like this, make sure that you are using correct parameters!

Upvotes: 0

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

This is your problem

#define BLOCK_HEAD_SIZE (ALIGN(sizeof(header)))

There's no such type as header in your program, which is what the compiler is telling you. You have defined type struct header and you have defined a typedef name block_header for it. So choose whichever you prefer: either sizeof(struct header) or sizeof(block_header). But not sizeof(header).

In C++ language defining a struct header type would also introduce typename header into the program. But not in C. In C the type defined by struct header is called struct header - two words. It cannot be shortened to a mere header.

Upvotes: 5

Related Questions