3

I was doing a project in C.And I am quite new to C. In the project, I have a struct like this :

struct room_t{
   char* name;
   struct room_t* north;
   struct room_t* east;
   struct room_t* south;
   struct room_t* west;
}

declared as : struct room_t room[3]

If I want to access the name in north, I do this :room[0].north[0]->name

Am I right ? or should it be room[0].north[0].name

3
  • the irst one is correct, since the fields (or properties) are pointers. well, it never hurt to give a shot. Commented Apr 29, 2017 at 13:12
  • 1
    It's a matter of type, just try it, one will compile and one will not. Though it would be poor form, assuming memory is correctly allocated, the "imo most readable" way would be room[0].north->name Commented Apr 29, 2017 at 13:15
  • There are no structs in your struct! What is unclear about dereferencing a pointer? Commented Apr 29, 2017 at 13:40

2 Answers 2

6

Your first guess is almost correct, but it should be room[0].north->name since you didn't declare an array for the variable north.

In general, you should give it a try and then see what outputs the compiler and your progam to learn as much as possible by yourself. ;)

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

Comments

4

It should be room[0].north->name, if you allocate single element in north But if you allocate an array(more than one element) into north, you should access as room[0].north[n].name where n=0 to (number of elements allocated) - 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.