3 ms·
I expect many people know this one, but it's a useful teaching aid when understanding the relationship between arrays and pointers int array[10]; *(array+1
by mhandley 2y ago
I expect many people know this one, but it's a useful teaching aid when understanding the relationship between arrays and pointers
int array[10];
*(array+1) = 56;
array[2] = 4;
3[array] = 27;
The first two are obvious, but the third is also legal. It works because array indexing is just sugar for pointer arithmetic, so array[2]=4 is identical in meaning to *(array+2)=4. Therefore 3[array]=27 is identical to *(3+array)=27 and so is legal. But just because you can doesn't mean you should.
- macintux 2y agoThe best, most entertaining book I've ever read on C covered that (unless I'm misremembering, but I doubt it): Expert C Programming. https://www.goodreads.com/book/show/198207.Expert_C_Programming https://www.goodreads.com/book/show/198207.Expert_C_Programm...
- dualogy 2y agoI'm already liking that one! Page 5 quote: > There is one other convention — sometimes we repeat a key point to emphasize it. In addition, we sometimes repeat a key point to emphasize it. One more quote and I'll stop: > ctime() converts its argument into local time, which will vary from GMT, depending on where you are. California, where this book was written, is eight hours behind London, and several years ahead
- WalterBright 2y ago> The first two are obvious, but the third is also legal. D doesn't have that bug! In 44 years of C programming, I've never encountered a legitimate use for the 3rd. (Other than Obfuscated C, that is.))
- mhandley 2y agoAgreed - I've only been programming C for 38 years but I've also never found a legitimate use. However I have used it to illustrate a point when teaching C to beginners - it looks so odd they tend to remember it.
- WolfeReader 2y agoIt's not a bug. You're seeing the difference between "this is how you're taught to access arrays" and "this is how array access actually works".
- WalterBright 2y agoSince the Standard specifies what that does, pedantically it is not a bug. Ok. But I call it a bug because it has no use and just pointlessly confuses people.
- im3w1l 2y agoWell it could (and I agree with WalterBright that it should) have been disallowed. a[b] being implemented as an early stage rewrite rule expanding to *(a+b) is an uninteresting implementation detail. And I doubt it is even implemented that way in modern compilers anyway. It certainly can't be in C++ as a[b] and b[a] mean different things when [] is overloaded.
- WolfeReader 2y agoThat "uninteresting implementation detail" is actually of grave importance when it comes to understanding how buffer overflow attacks work. I hate to think anyone would put C code into production without understanding this.
- kragen 2y agoYou seem to be lecturing the author of one of the most prominent early C compilers on how array access actually works in C.
- WolfeReader 2y agoYep.