K
Kaz Kylheku
Hi, every1 (quick question):
Is this valid C89 code?
I was doing a problem from a previous programming competition and I
ridded the program of every error except for one which I believe is
associated with the following:
typedef struct something {
int variable;
} lots[100];
Just a guess; you might have run into trouble by creating a typedef
name for an array type.
Why isn't this allowed? I should probably create a tiny program
containing this code and compile it b4 I ask though.
Arrays are not first class objects in C, and typedef is only an aliasing
facility; it can only give a name to an existing type, not create a new
abstraction.
So after the above typedef, the identifier ``lots'' represents a type:
an array of 100 elements of ``struct something''.
But this won't work:
lots give_me_lots(void)
{
lots l;
/* fill in l[0].variable through l[99].variable */
return l;
}
You cannot return arrays from functions in C. This calls for a diagnostic
message.
And the following will appear to be passing lots by value, but
in fact the argument l is a pointer to the first element,
allowing the function to modify the caller's object:
// sneaky: looks like regular C call-by-value;
// no [] syntax in sight to give it away!
void work_with_lots(lots l)
{
l[0].value = 42; // ha!
}
You also might have possibly run into this. Here, l is a pointer
to an aray:
void initialize_lots(lots *l)
{
int i;
for (i = 0; i < 100; i++) {
/* Awkward syntax: dereference pointer to arrray
in parentheses to refer to the array, then
apply array indexing. */
(*l) = i;
}
}
So all in all, typedef names for arrays, unless they are just used as
intermediates for defining another type, are probably going to bring
confusion into your program.