c - What does "char *t = s + len" mean? -


I am going through a programming book and I am wondering what a line of code is

Below is a function that takes a character array and prints backwards.

  void print_reverse (Char * s) {size_t len ​​= strlen (s); Char * t = s + len -1; // I do not know what this line is doing (T & gt; = s) {printf ("% c", * t); T = T - 1; }     Puts(""); }  

Assume that s is the string "PaxDiablo" is stored in memory at the place 1 as follows:

  s | V + --- --- --- --- --- --- ------- + + + + + ---- + | P | One | X | D | I One | B L O | \ 0 | + --- --- --- --- ------ Address: 1 2 3 4 5 6 7 8 9 10  

expression t = s + len - 1 (where lane is 9 in this case) set T to s for eight characters.

  st | | VV + --- --- --- --- --- ------ | P | One | X | D | I One | B L O | \ 0 | + --- --- --- --- ------ Address: 1 2 3 4 5 6 7 8 9 10  

In other words, it gives you the address of the last character in the string.

The rest of the code then goes back to s on the string again after reducing t in the rear direction.


Technically, this is an undefined behavior. You only want to compare each pointers where they point to a letter beyond one character (here we are t , where it is a letter first array), but you will struggle to find the system on which it does not work.

As potposewater (I absolutely love some names choose such people from here) Comment, you can avoid that comparison using the instead of while {} :

  #include & lt; Stdio h & gt; #include & lt; String.h & gt; Zero PrintRaws (four * straws) {size_t len ​​= strlen (str); If (lane! = 0) {char * pStr = str + len; Do {puncher (* (- PST)); } While (PSTR> str); } Cursed ('\ n'); }  

Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -