Understanding C Arrays and Pointers

It’s a bit of help to understand what exactly is happening in this piece of code. When I run the program, it prints 7.

#include <stdio.h> int main() { int a[] = {1,2,3,4,5,6,7,8,9}; int b[] = {1,2,3,4,5,6,7,8,9}; int c = 5; int *p = a; printf("--> %d", (c[b])[p]); return 0; } 

I'm a little confused when it comes to the (c [b]) [p] part of the printf statement. Any help / explanation would be greatly appreciated.

+5
source share
1 answer

It's a little strange to write like that, but the [] operator in C is commutative. This means that (c[b])[p] same as p[b[c]] , which is much easier to understand:

 p[b[c]] = p[b[5]] = p[6] = a[6] = 7 

Doing the same with the original expression will also work, it's just a little strange to look in places:

 (c[b])[p] = (5[b])[p] = (b[5])[p]) = 6[p] = p[6] = a[6] = 7 

Commutativity (if this word) from [] occurs only because of its definition, i.e. a[b] same as *(a + b) , where you can see the order of a and b does not matter.

+13
source

Source: https://habr.com/ru/post/1208974/


All Articles