On Mon, 19 Jul 2004, lallous wrote:
l>>
l>> " int tlr_val[1]; "
l>> Is there any specific purpose behind this kind of declaration ?
l>
l>I see such declaration useful in something similar to:
l>
l>typedef struct
l>{
l> char x, y, z;
l> int tlr_val[1]; // variable length array that belongs to the struct
l>} theType;
[and then goes on to access tlr_val[n] for n>0]
Note that this is not portable C. It will obviously crash on a
system that does array bounds checking, and possibly on other systems
as well.
That's better be done by declaring
struct {
...
int tlr_val[];
};
(It ought to be noted that this is new in C99, and is an error in
earlier C standards.)
As for the original question: it could be used to prevent
accidential copying.
Or just because we needed an array of one element for some reason,
possibly to pass to or from another function. You /could/ replace
all arrays of one element with single objects, but that would often
murk up the code. Contrived example:
#define TYP_FOO 1
#define TYP_BAR 2
#define TYP_EMPTY 3
int gettype() { return /* pick something */; }
char *getbuffer(int typ);
char *getstring(int typ);
int main()
{
int typ = gettype();
char *buffer = getbuffer(typ);
sprintf(buffer, "%s", getstring(typ));
printf("The result is %s\n", buffer);
}
char *getbuffer(int typ)
{
static char bigbuffer[1000], smallbuffer[100], tinybuffer[1];
switch (typ) {
case TYP_FOO: return bigbuffer;
case TYP_BAR: return smallbuffer;
case TYP_EMPTY: return tinybuffer;
}
}
char *getstring(int typ)
{
switch (typ) {
case TYP_FOO: return "foo";
case TYP_BAR: return "bar";
case TYP_EMPTY: return "";
}
}
HTH,
-Arthur