user defined concatenation function

时间:2019-02-18 00:37:45

标签: c

I'm learning C and I came across the below code which implements concatenation but I am struggling to understand the second portion despite recapping pointer/increment precedence and associativity.

I have run examples of all the different combinations of dereferencing and post/pre increment and now recall that pre-increment with dereferencing is right to left associative e.g *++q where the inc would occur first. The page I learned from stated that post-increment with the dereference operator has the increment as higher precedence and goes on to say that the associativity of this example is left to right. I don't particularly know why it mentions the associativity as I understand precedence is regarded before it e.g *p++ would increment before its dereference.

The below code starts by recursively calling itself with a pre-inc on dest to get to the end of the destination string which is denoted by it reaching and dereferencing the null byte. At this point, I lose track because I would have thought it would simply the dereferenced dest to the dereferenced src however it post increments it which based off what I've learned would increment to the memory location after the null byte dereference it and proceed to assign the string "eeksfor" to the position above the null byte in dest. Not only does this confuse me but the program goes on to call itself in another ternary operator / return 0 for seemingly no reason.

Thanks

/* my_strcat(dest, src) copies data of src to dest.  To do so, it first           reaches end of the string dest using recursive calls my_strcat(++dest, src).         Once end of dest is reached, data is copied using  
(*dest++ = *src++)?  my_strcat(dest, src). */
void my_strcat(char *dest, char *src) 
{ 
  (*dest)? my_strcat(++dest, src): (*dest++ = *src++)? my_strcat(dest,   src): 0 ; 
} 

/* driver function to test above function */
int main() 
{ 
  char dest[100] = "geeksfor"; 
  char *src = "geeks"; 
  my_strcat(dest, src); 
  printf(" %s ", dest); 
  getchar(); 
}     

I ran the program and it does what it is expected to do. That is it returns the string "geeksforgeeks" so clearly I'm just not understanding something

1 个答案:

答案 0 :(得分:3)

好吧,所以您知道第一个递归位很好(保持dst递增以找到结尾)。

找到结束之后,就该开始复制了。它用于复制一个字节的代码是:(* dest ++ = * src ++)

将代码扩展为类似以下内容可能会帮助您理解:* dest = * src;目标+ = 1; src + = 1 (因为它们是后增量运算符)

现在,正常的“复制”功能会在 while for 循环中重复该语句,但是由于我们巧妙地展示了它,我们使用了第二个三元运算符和递归。最终的“ 0”并没有真正做任何事情,但它必须作为三元运算符的“ else”部分存在。

虽然这可能不是有史以来最糟糕的 strcat 实现,但它无疑是一个有力的竞争者。