[prog] C language: structures containing structures

Meredith L. Patterson mlp at thesmartpolitenerd.com
Thu Nov 4 07:06:51 EST 2004


aec wrote:
> ex.9.5.c:51: error: incompatible type for argument 1 of `timekeeper'
> 
> line 51 is: 
> 
> later.sDate = timekeeper(later.sDate); 

Take a look at the prototype for timekeeper():

 > struct dateAndTime timekeeper(struct dateAndTime current)

later.sDate is a date struct; the function requires a dateAndTime 
struct. If you just pass in later, you should be fine.

> This is topic is not clealy discussed in my C book so Im kinda
> confused at the moment. 

It's a level of indirectness, which is always a bit confusing -- I've 
run into the same problem plenty of times myself. FWIW, this is often a 
good reason to define accessor functions when you plan to operate on the 
guts of a data structure; that way, you can quickly check the return 
type rather than having to dig through your code.

(This isn't actually so helpful in C, because structs can't have member 
functions, but you could have something like

   date getDate(struct dateAndTime foo) {
	return foo.sDate;
   }
   time getTime(struct dateAndTime foo) {
	return foo.sTime;
   }

Then, later on, when you wanted to call timekeeper(), if you called it like

	timekeeper(getDate(later));

the fact that getDate()'s return type is date should throw you a red 
flag saying "whoops, I'm passing the wrong parameter type to 
timekeeper()!" Anyway, it's much more useful in C++, where you can give 
member functions to classes (so you'd have syntax like later.getDate()), 
but you can do it in C anyway if you want to.)

Hope this helps!

Cheers,
Meredith


More information about the Programming mailing list