C declarations (with examples)
Ray Lubinsky
rwl at uvacs.UUCP
Wed Jan 30 11:25:08 AEST 1985
> I have a question about C declarations. The [] notation is equivalent
> to the * notation, right?
Well, not exactly. To declare something as ptr[] is to say that you want
an array of objects of the type that you specify and that the identifier 'ptr'
is to point to the zeroth element. Declaring *ptr only reserved 'ptr' to mean
a pointer to that type. For example here are the errors I got on two test
programs:
% cat > test1.c <<EOF | % cat > test2.c <<EOF
main() { | char x[];
char y[]; | main()
y = "abc"; | {
} | }
EOF | EOF
% cc test1.c | % cc test2.c
"test1.c", line 3: illegal lhs of | Undefined:
assignment operator | _x
In test1, the compiler tells us that you can't change the value of the
identifier which indicates the start of an array. No matter that they array
has no elements -- it just won't permit it. Otherwise, a programmer could
lose track of his array. In test2, the compiler assumes that the (evidently)
null array 'x' must be declared in some other load module; when it's not found,
the loader complains.
When you declare an array, you must define how much storage you want to
allocate for it. There are three possiblities:
int x[2]; /* x points to a block of 2 elements */
int y[] = { 0 , 1 }; /* y has implicitly 2 elements */
extern int z[]; /* z has dimensions declared elsewhere */
If you have a pointer to integer call 'ptr', it can be assigned to point to
an element of any of these arrays. The statement ptr = z; just points 'ptr'
to the zeroth element of array z.
> Is this a desirable characteristic of C?
What can I say? C will let you do all sorts of crazy things that you had no
intention of doing (like accessing the 11th element of a ten-element array) but
it won't let you risk losing all references to a block of allocated memory.
Seems like a good idea to me.
------------------------------------------------------------------------------
Ray Lubinsky University of Virginia, Dept. of Computer Science
uucp: decvax!mcnc!ncsu!uvacs!rwl
More information about the Comp.lang.c
mailing list