[Solved] Pointer C Language [closed]


What does this function do?

It concatenates two strings, i.e. it’s doing the same as the standard strcat function. See https://man7.org/linux/man-pages/man3/strcat.3.html

Assume the input is “Hello World”.

Just when the function is called, some where in memory it looks like:

String1: Hello\0
         ^
         |
         s1

String2: World\0
         ^
         |
         s2

Now this part

while (*s1 != '\0') {
  ++s1;
} 

Moves the pointer s1 to the end of String1. So you have

String1: Hello\0
               ^
               |
               s1

String2: World\0
         ^
         |
         s2

Then this part

for (; *s1 = *s2; ++s1, ++s2) {
  ; // empty statement
} 

copies characters from String2 (using s2) to the end of String1 (using s1).

After one loop, you’ll have:

String1: HelloWorldW
                    ^
                    |
                    s1

String2: World\0
          ^
          |
          s2

After one more loop, you’ll have:

String1: HelloWorldWo
                     ^
                     |
                     s1

String2: World\0
           ^
           |
           s2

and so on.

In the end you’ll have

String1: HelloWorld\0
                     ^
                     |
                     s1

String2: World\0
                ^
                |
                s2

Net result: String2 was concatenated to String1

A few more words about for (; *s1 = *s2; ++s1, ++s2) {

The ; says: no initialization needed

The *s1 = *s2; says: Copy the char that s2 points to to the memory that s1 points to. 
Further, it serves as "end-of-loop" condition, i.e. the loop will end when a \0 has 
been copied

The ++s1, ++s2 says: Increment both pointers

In this way characters from String2 are one-by-one copied to the end of String1

BTW: Notice that the main function is unsafe as too little memory is reserved for String1

0

solved Pointer C Language [closed]