-2

I'm having issue with a struct I have created

typedef struct _BLOCK
{
    int size;
    int offset;
    Block *nextBlock;

} Block;

the compiler doesn't recognise the identifier for the *nextBlock pointer

also compiler doesn't seem to recognise the "Block" struct at any point in the program, i use it as an argument in a few methods and errors like "syntax error: missing '{' before '*'" occur. any insights would be helpful

David
  • 11
  • 5

2 Answers2

1

You are missing a semicolon:

struct _BLOCK *nextBlock;
simpel01
  • 1,792
  • 12
  • 13
  • 2
    @David Also, that should be `struct _BLOCK *nextBlock;` since the compiler reads from top to bottom and when it sees `Block *nextBlock;`, it will be like 'Hey, what's `Block`? I haven't seen it being defined anywhere' and will throw an error. – Spikatrix Apr 25 '16 at 16:32
  • @CoolGuy yeah your right, appreciate the help – David Apr 25 '16 at 16:33
1

The missing semicolon doesn't help, but you have a bigger issue.

The typedef name Block isn't introduced until after the struct definition is complete, so you can't use it in the declaration for nextBlock. You have two choices at this point:

  1. Use struct _BLOCK for the declaration:
    struct _BLOCK *nextBlock;
  2. Forward declare the struct and typedef name:
    struct _BLOCK;
    typdef struct _BLOCK Block;
    struct _BLOCK {
      ...
      Block *nextBlock;
      ...
    };
    

Nits:

Do not use leading underscores for your variable or type names; such names are reserved for the implementation. IOW, the compiler may define a symbol _BLOCK for its own purposes, and your use of _BLOCK may lead to a namespace collision. Use struct BLOCK or struct Block or something like that instead.

Also, be judicious in your use of typedefs. If anyone using Block has to be aware that it's a struct type, then you're better off just using struct Block. Look at the FILE type as an example; you are not meant to manipulate the contents of a FILE object directly, you just pass a pointer to it to the various stdio routines. You, as the programmer, don't need to know what a FILE object looks like on the inside, so in that case it's appropriate to hide it behind a typedef.

If anyone using your Block type has to access the size, offset, or nextBlock members directly, then it's better make its struct-ness explicit. OTOH, if you're providing an API to manipulate or access block members (similar to the FILE type and stdio routines), then the typedef is okay.

Never hide pointers behind typedefs.

John Bode
  • 119,563
  • 19
  • 122
  • 198