Sujet : Arrays
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.cDate : 29. Sep 2024, 12:33:33
Autres entêtes
Organisation : Stefan Ram
Message-ID : <UB-20240929123144@ram.dialup.fu-berlin.de>
Alright, so I've got a triple whammy of questions coming at me.
It's about this program I've been tinkering with.
#include <stdio.h>
int main()
{ char const abc[] = "abcdefhijklmnopqrstuvwxyz";
char const * const p = abc + 3;
char const( * const def )[] =( char const( * const )[] )p;
printf( "%c\n",( *def )[ -3 ]); }
1st
First off, I'm getting this warning that's throwing me for a loop:
main.c: In function 'main':
main.c:7:32: warning: cast discards 'const' qualifier from pointer target type [-Wcast-qual]
7 | char const( * const def )[] =( char const( * const )[] )p;
| ^
So I'm wondering: How can I dodge this discarding the constness
warning?
2nd
Then I'm hit with another warning:
main.c:7:3: warning: dereferencing type-punned pointer might break strict-aliasing rules [-Wstrict-aliasing]
7 | char const( * const def )[] =( char const( * const )[] )p;
| ^~~~
What's this warning trying to tell me?
3rd
But the real head-scratcher is that "-3" in the last line.
On paper, we're crunching numbers to get the address of
a spot before the object (the object being "( *def )"),
so technically we're in undefined behavior territory.
But here's the kicker - we know that spot is still chilling in the
"abc" array. Does the language standard have any loopholes that
might save our bacon here and make this not undefined after all?
TIA!