0
void s1(char dest[], char src[])
{
    int i=0;
    while(dest[i++]=src[i++]);
}

void s2(char * dest, char *src)
{
    while(*dest++=*src++);
}

Also, note that I took this problem from a book, and don't know if the code is correct or not(I think there should be two '=' in the while loop)

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Akos Nagy
  • 23
  • 2
  • 2
    It's just a few lines of code; couldn't you at least *try* and format it properly before posting? – r3mainer Feb 06 '17 at 16:06
  • Possible duplicate of [Difference between passing array and array pointer into function in C](http://stackoverflow.com/questions/5573310/difference-between-passing-array-and-array-pointer-into-function-in-c) – msc Feb 06 '17 at 16:08
  • @Akos Nagy, Re "*I think there should be two '=' in the while loop*", No, then it won't copy anything. The functions are (attempts to) reimplement `strcpy`. – ikegami Feb 06 '17 at 16:12
  • @minigeek, Re "*Its an infinite loop basically since it is =*", No, it stops after copying a NUL. The functions are (attempts to) reimplement `strcpy`. – ikegami Feb 06 '17 at 16:13
  • did it not tell you in the book? – WhatsThePoint Feb 06 '17 at 16:31

2 Answers2

5

The second code performs a string copy. It is equivalent to strcpy().

The first code has undefined behaviour because it updates i twice in one statement without an intervening sequence point.

So the answer is that they are not the same.

The first code could be corrected. For example like this:

void s1(char dest[], char src[])
{
    int i=0;
    while(dest[i]=src[i]) i++;
}
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
0

For starters these function declarations

void sh1(char dest[], char src[]);

and

void s2(char * dest, char *src);

are equivalent because function parameters declared like arrays are adjusted to pointers to objects with types that corresponds to the array element types.

You even can include in one compilation unit the both declarations of a function with the same name and they will declare the same one function (though the function definition must be one provided that the function is not an inline function).

So the question is about whether the expressions used in the loops that is

while(dest[i++]=src[i++]);

and

while(*dest++=*src++);

yield the same result.

The first loop has undefined behavior. You should rewrite it like

while(dest[i] = src[i]) i++;

As for example dest++ increases the pointer it can be rewritten like dest = dest + 1. Thus applying the operator ++ several times to the pointer you will get that it is equivalent to the expression dest = ( dest + 1 ) + 1 + ... +1; Ot it can be written like dest = dest + i; where i is the sum of 1 + 1 ...+ 1

So for each iteration of the loops these expressions

*dest++ and dest[i], i++

yield the same result.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335