This example compiles without warnings/errors (gcc 4.8.2 -Wall):
#include <stdio.h>
int main()
{
char c;
int i;
printf("%p %02x\n",&i,c[&i]);
printf("%p %02x\n",&c,c[&c]);
// important to note that this line DOESN'T compile:
//printf("%p %02x\n",&i,c[i]);
// which makes sense as c is NOT an array, it is a char.
return 1;
}
Why does the syntax c[&i] compile ? Is it intentional or an accident? Is the syntax c[&i] semantically valid ? (Does it have any useful meaning?)
Example of output for me: (pointers change each time)
0xbfb2577c b7718cea
0xbfb2577b 08
This question originated from a strange bit of code 'ch2[&i]' in question here: C duplicate character,character by character
NOTE#0 (updated, upon reflection) on duplicates/similar questions: This question is not a duplicate of the linked questions on c array references. It is related so it is useful to refer to them. The related questions discuss the valid a[b] and b[a] case where one of a or b is a pointer and the other is an int. This question deals with the more weird and maybe should be invalid case where one of a or b is a char. With C arrays, why is it the case that a[5] == 5[a]? 14 answers With arrays, why is it the case that a[5] == 5[a]? String as an array index 3 answers String as an array index
NOTE #1: This happens with compiler as the type of variable c is char and that can be used as index into array when combined with pointer.
NOTE #2: for some reason, type of c[<ptr>]
evaluates to type of <ptr>
.
E.g.: the resulting types of c[&pi]
and c[&pc]
cause warnings in the following code:
int *pi; char *pc; pi=&i; pc=&c;
printf("%p %02x\n",&pi,c[&pi]);
printf("%p %02x\n",&pc,c[&pc]);
Warnings on type 'int *' or 'char *' instead of 'unsigned int':
c/so_cweirdchar2.c: In function ‘main’:
c/so_cweirdchar2.c:13:5: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘int *’ [-Wformat=]
printf("pi %p %02x\n",&pi,c[&pi]);
^
c/so_cweirdchar2.c:14:5: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘char *’ [-Wformat=]
printf("pc %p %02x\n",&pc,c[&pc]);
^