[7972603] | 1 | #include <assert.h>
|
---|
| 2 | int main() {
|
---|
[df699e0] | 3 | float ar[10]; $\C{// array}$
|
---|
| 4 | float (*pa)[10] = &ar; $\C{// pointer to array}$
|
---|
| 5 | float a0 = ar[0]; $\C{// element}$
|
---|
| 6 | float * pa0 = &(ar[0]); $\C{// pointer to element}$
|
---|
[266732e] | 7 |
|
---|
[df699e0] | 8 | float * pa0x = ar; $\C{// (ok)}$
|
---|
[266732e] | 9 | assert( pa0 == pa0x );
|
---|
[df699e0] | 10 | assert( sizeof(pa0x) != sizeof(ar) );
|
---|
[266732e] | 11 |
|
---|
[0554c1a] | 12 | void f( float x[10], float * y ) {
|
---|
| 13 | static_assert( sizeof(x) == sizeof(void *) );
|
---|
| 14 | static_assert( sizeof(y) == sizeof(void *) );
|
---|
[266732e] | 15 | }
|
---|
[df699e0] | 16 | f( 0, 0 );
|
---|
[266732e] | 17 |
|
---|
| 18 | // reusing local var `float a[10];`}
|
---|
| 19 | float v;
|
---|
[df699e0] | 20 | f( ar, ar ); $\C{// ok: two decays, one into an array spelling}$
|
---|
[5546f50b] | 21 | f( &v, &v ); $\C{// ok: no decays; a non-array passes to an array spelling}$
|
---|
[266732e] | 22 |
|
---|
[5546f50b] | 23 | char ca[] = "hello"; $\C{// array on stack, initialized from read-only data}$
|
---|
[0554c1a] | 24 | char * cp = "hello"; $\C{// pointer to read-only data [decay here]}$
|
---|
| 25 | void edit( char c[] ) { $\C{// parameter is pointer}$
|
---|
[266732e] | 26 | c[3] = 'p';
|
---|
| 27 | }
|
---|
[5546f50b] | 28 | edit( ca ); $\C{// ok [decay here]}$
|
---|
[0554c1a] | 29 | edit( cp ); $\C{// Segmentation fault}$
|
---|
[5546f50b] | 30 | edit( "hello" ); $\C{// Segmentation fault [decay here]}$
|
---|
[266732e] | 31 |
|
---|
[520fa9e] | 32 | void decay( @float x[10]@ ) {
|
---|
| 33 | static_assert(@sizeof(x) == sizeof(void *)@ );
|
---|
[266732e] | 34 | }
|
---|
[df699e0] | 35 | static_assert( sizeof(ar) == 10 * sizeof(float) );
|
---|
| 36 | decay( ar );
|
---|
[266732e] | 37 |
|
---|
[520fa9e] | 38 | void no_decay( @float (*px)[10]@ ) {
|
---|
| 39 | static_assert(@sizeof(*px) == 10 * sizeof(float)@);
|
---|
[266732e] | 40 | }
|
---|
| 41 | static_assert( sizeof(*pa) == 10 * sizeof(float) );
|
---|
[df699e0] | 42 | no_decay( pa );
|
---|
[7972603] | 43 | }
|
---|
[266732e] | 44 |
|
---|
| 45 | // Local Variables: //
|
---|
[df699e0] | 46 | // compile-command: "sed -f sedcmd bkgd-carray-decay.c | gcc-11 -Wall -Wextra -x c -" //
|
---|
[266732e] | 47 | // End: //
|
---|