- 论坛徽章:
- 0
|
学习c语言的时候,自己做练习写了个 strcat() 函数,代码如下,我这里直接把指针传递给函数后,在函数内部改变了指针的指向,
而得到的结果却是正确的,我以为我这么写就是ok的,
结果参考glibc里面 /string/strcat.c 的实现,发现它居然是另外定义了两个指针来分别代替传递进来的数组指针,运算完后,返回原dest的首地址。
glibc的实现肯定是有深意的,那么它为什么要重新定义两个指针来代替原指针做运算呢?为了返回值dest(函数内部的操作不影响外部值?)?或者其他,希望大家能帮我解惑,谢谢。
这个是我写的练习- #include<stdio.h>
- #define MAX 100
- char *mystrlen(char *s, char *t);
- int main()
- {
- char s[MAX] ="abcd";
- char *t = "efg";
- mystrlen(s,t);
- printf("%s\n",s);
- }
- char *mystrlen(char *s, char *t)
- {
- for(; *s != '\0'; s++)
- ;
- while (*s++ = *t++)
- ;
- return s;
- }
复制代码 这个是 glibc中的strcat.c 的实现- #include <string.h>
- #include <memcopy.h>
- #undef strcat
- /* Append SRC on the end of DEST. */
- char *
- strcat (dest, src)
- char *dest;
- const char *src;
- {
- char *s1 = dest;
- const char *s2 = src;
- reg_char c;
- /* Find the end of the string. */
- do
- c = *s1++;
- while (c != '\0');
- /* Make S1 point before the next character, so we can increment
- it while memory is read (wins on pipelined cpus). */
- s1 -= 2;
- do
- {
- c = *s2++;
- *++s1 = c;
- }
- while (c != '\0');
- return dest;
- }
- libc_hidden_builtin_def (strcat)
复制代码 |
|