1

I'm relatively new to C and trying to understand structs and pointers. What does the *Building at the end of this struct declaration do?

typedef struct building {
        char *floor;
        struct building *nextBuilding;
} *Building;

Does it mean that from now on when I do

Building someBuilding = malloc(sizeof(struct building));

somebuilding is a pointer to a building?

Apollo
  • 8,874
  • 32
  • 104
  • 192

2 Answers2

2

To answer the question: yes. You now have a type Building that is a pointer to a struct building and you can do this:

Building someBuilding = malloc(sizeof(struct building));
someBuilding->floor = malloc (sizeof(char)*20);
strcpy(someBuilding->floor, "First floor");
someBuilding->nextBuilding = NULL;

etc.

note that this might not be a good idea in all cases. For example if you declare a method:

void setFloorName(Building building, char* name)

you can't really tell that you need to pass a pointer to a building struct, but if you do:

void setFloorName(Building* building, char* name)

you immediately see that the function takes a pointer.

jpw
  • 44,361
  • 6
  • 66
  • 86
2

Yes, when you write:

 typedef struct building { … } *Building;

 Building bp;

then bp is a pointer to a struct building. However, it is frequently regarded as bad style to include the pointer in the typedef; code is easier to understand if you use:

 typedef struct building { … } Building;

 Building *bp;

Now it is clear looking at the definition of bp that the type is a pointer. If you are never going to access the internals of the structure, then it doesn't matter too much (but look at FILE * in <stdio.h>; you always write FILE *fp, etc). If you're going to access the internals:

printf("Floor: %s\n", bp->floor);

then it is better to have the pointer visible. People will be mildly surprised to see Building bp; and then later bp->floor instead of bp.floor.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • interseting because my cs professor used *Building in his code. Thanks – Apollo Mar 17 '14 at 02:34
  • 1
    Professors do not have a monopoly on good style. It is an area where people disagree, but I think you'd find a fair number of people agree with me. See, for example, [Typedef pointers — a good idea?](http://stackoverflow.com/questions/750178/typedef-pointers-a-good-idea) – Jonathan Leffler Mar 17 '14 at 02:51