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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

interseting because my cs professor used *Building in his code. Thanks
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?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.