Monday 12 November 2018

c - Subscripting integer variable using a pointer











Today I came across this blog. What attracted me the most is this:



int i;
i["]



Well, I don't really know what is the purpose of the weird "string constant" inside the array subscript, but I am confused how it is possible to subscript an integer variable. So I came with this code:



#include 

int main(void) {
int x = 10;

printf("%d", x["\0"]); /* What is x["\0"]?! */

return 0;


}


It compiles without error using MinGW with -Wall -ansi -pedantic. This code then outputs: 105.



Can anyone interpret this?



Edit: I found that there must be a pointer inside the subscript, or else I get compile-time error.


Answer




It's a well-known trick. Because of the way pointer arithmetic works, the following are synonymous:




  • v[5]

  • 5[v]

  • *(v + 5)



It's the same thing when v happens to be a string literal.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...