Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this C array reference look incorrect?

Tags:

c

Below is a piece of code copied from a website. The value set for the direction prints the respective character from "nsew". For example the output of this code is character w.

I am wondering how does it work.

#include<stdio.h>
void main (void){
   int direction = 3;
   char direction_name = direction["nsew"];
   printf("%c",direction_name);
}
like image 692
bubble Avatar asked Dec 06 '12 20:12

bubble


People also ask

How do you reference an array in C?

C arrays are declared in the following form: type name[number of elements]; For example, if we want an array of six integers (or whole numbers), we write in C: int numbers[6];

Why are reference arrays not allowed?

An array of references is illegal because a reference is not an object. According to the C++ standard, an object is a region of storage, and it is not specified if a reference needs storage (Standard §11.3. 2/4). Thus, sizeof does not return the size of a reference, but the size of the referred object.

Is array always passed by reference in C?

Arrays are always pass by reference in C. Any change made to the parameter containing the array will change the value of the original array. The ampersand used in the function prototype. To make a normal parameter into a pass by reference parameter, we use the "& param" notation.

How do you declare an array reference variable?

An array reference variable is declared by the use of brackets.


2 Answers

This is because the array subscript operator is commutative, i.e., this:

const char *p = "Hello";
char x = p[0];

Is equivalent to

const char *p = "Hello";
char x = 0[p];

Weird, huh? In your case you are indexing into the third position of the string literal (which is an array) "nsew".

some_ptr[n] is equivalent to *(some_ptr + n), and since addition is commutative, it is also equivalent to *(n + some_ptr). It then follows that n[some_ptr] is also an equivalent expression.

I wouldn't recommend using this "feature" however... seriously, don't do it.

like image 78
Ed S. Avatar answered Oct 13 '22 10:10

Ed S.


Operator [] has the same semantics as pointer arithmetics. So a[i] is equivalent to *(a + i) which is equivalent to *(i + a) which is equivalent to i[a]:

So direction["nsew"] == "nsew"[direction] == "nsew"[3] == 'w'

like image 42
Rost Avatar answered Oct 13 '22 08:10

Rost