Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing 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 what I can't understand is the expression b+(c-*a)-2. Can someone be kind and break it down?

like image 579
Pithikos Avatar asked Feb 22 '23 21:02

Pithikos


1 Answers

  • b+(c-*a)-2 is the same as &b[(c-*a)-2]. In other words, if (c-*a)-2 is an offset into string b, puts(b+(c-*a)-2) would print the string b starting from the position at the (c-*a)-2 offset.
  • c is assigned *(a+1), or *(&(a[1])), or simply a[1], which points to "big"
  • Count the squares on your diagram to find the value of c-*a (it is 5)
  • b[5-2] is "ing"

Disclaimer: if anyone tried to check in such code at my company, he would no longer be working for us.

like image 157
Sergey Kalinichenko Avatar answered Feb 26 '23 12:02

Sergey Kalinichenko