An Interesting Pointer Puzzle
denniskubes.comSomething is overlooked. Note that:
int *a[] = { 1, 2, 3 }
violates a constraint in the C language; an ISO C conforming implementation must issue a diagnostic --- and, additionally, it may stop translating and reject the program.Why? Because expressions of type int are being used to initialize elements of type pointer to int, without a cast.
The first step is operating your compiler such that you get the required diagnostics out of it, or at least the important ones, and then some. For instance, with gcc:
# C90
gcc -Wall -ansi ... # some would add -pedantic
# C99
gcc -Wall -std=c99 ...
and then, don't ignore diagnostics that are "mere" warnings!And, of course, passing a pointer argument to a "%d" conversion specifier in printf is undefined behavior.
You're correct. I wasn't trying to say this was the way to code. In fact I pointed out that we were ignoring warnings on purpose. The interesting part, at least to me, is that the output of the logic errors were consistent leading to a nice example of bad pointer math. Understanding how the compiler is seeing the code was illuminating.
What do you mean by "bad"; what calculation do you intend to label that way?
In the sequence 0, 4, 8, 12, 16 the deltas are equal, and consistent with the size of an int in bytes.
It looks bad when we don't know it's pointer math, and/or are not aware that the syntax we used doesn't index into the array; if we know these things, it is unsurprising.
Now if you got the Fibonacci sequence, that would be astonishing! :)