Print a string in C with pointer arithmetic, including arrays, integers and pointers

There are three structures; arrays a and b and pointer c :

 c --------------------------. | V ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ a --> | a | \0| \0| \0| \0| b | i | g | \0| \0| r | i | d | e | \0| ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ___ ___ ___ ___ ___ ___ ___ b --> | F | l | y | i | n | g | \0| ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด ยดยดยด 

This is the code:

 int main(){ char a[3][5]={"a", "big", "ride"}; char b[]="Flying"; char *c=*(a+1); puts(b+(c-*a)-2); return 0; } 

Now I can not understand the expression b+(c-*a)-2 . Can someone be kind and break it?

+4
source share
1 answer
  • b+(c-*a)-2 same as &b[(c-*a)-2] . In other words, if (c-*a)-2 is the offset in line b , puts(b+(c-*a)-2) will print line b starting at the position in the offset (c-*a)-2 .
  • c assigned *(a+1) or * (& (a [1])) or just a[1] , which indicates "big"
  • Count the squares on the chart to find the value c-*a (this is 5)
  • b[5-2] "ing"

Disclaimer: if someone tries to check such a code in my company, it will no longer work for us.

+8
source

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


All Articles