B
BartC
I've heard of 'declaration reflects use' many times, in connection with
helping decode complex type declarations, although it's never really worked
for me. Until I played with the following code. The declaration and use of
the indirect 'c' array match perfectly!
#include <stdio.h>
#include <stdlib.h>
#define N 10
int main(void) {
int a[N];
int *b;
int (*c)[];
int i;
b=malloc(N*sizeof(int));
c=malloc(N*sizeof(int));
for (i=0; i<N; ++i) {
a=i*20;
b=i*30;
(*c)=i*40;
}
for (i=0; i<N; ++i) {
printf("%d: %4d %4d %4d\n",i,a,b,(*c));
}
}
'a' declares a normal int array of a size known at compile time.
'b' declares a pointer to an int array to be set up at runtime, but in the
conventional way used in C, by declaring instead a pointer to an int, the
element type.
'c' does it a little differently, by declaring a pointer to an actual int
array.
'Declaration reflects use' describes c aptly, but seems to have no bearing
on the declaration and use of b!
(I can understand why 'b' is preferred, the indexing is much simpler and
more readable, and ties in with pointers and arrays being interchangeable.
But I'm generating C source from a language where the 'c' way makes far more
sense type-wise, plus I don't have look at the C code very often.)
(BTW, on my machine, I use a magic version of malloc() that will never fail
for these tiny test programs.)
helping decode complex type declarations, although it's never really worked
for me. Until I played with the following code. The declaration and use of
the indirect 'c' array match perfectly!
#include <stdio.h>
#include <stdlib.h>
#define N 10
int main(void) {
int a[N];
int *b;
int (*c)[];
int i;
b=malloc(N*sizeof(int));
c=malloc(N*sizeof(int));
for (i=0; i<N; ++i) {
a=i*20;
b=i*30;
(*c)=i*40;
}
for (i=0; i<N; ++i) {
printf("%d: %4d %4d %4d\n",i,a,b,(*c));
}
}
'a' declares a normal int array of a size known at compile time.
'b' declares a pointer to an int array to be set up at runtime, but in the
conventional way used in C, by declaring instead a pointer to an int, the
element type.
'c' does it a little differently, by declaring a pointer to an actual int
array.
'Declaration reflects use' describes c aptly, but seems to have no bearing
on the declaration and use of b!
(I can understand why 'b' is preferred, the indexing is much simpler and
more readable, and ties in with pointers and arrays being interchangeable.
But I'm generating C source from a language where the 'c' way makes far more
sense type-wise, plus I don't have look at the C code very often.)
(BTW, on my machine, I use a magic version of malloc() that will never fail
for these tiny test programs.)