自定义strcpy函数不返回预期指针

use*_*211 1 c

#include<stdio.h>
#include<stdlib.h>
char *str_cpy(char *, char *);
void main()
{
    char *desti= (char *)calloc(sizeof(char),10);
    char *m= (char *)calloc(sizeof(char),10);
    m = str_cpy(desti,"dhawal");
    printf("destination string is :%s\n",desti);
    printf("%s\n",m);

}

char *str_cpy(char *a,char *b)
{
    while(*b!='\0')
    {
        *a = *b;
        a++;
        b++;
    }
    *a = '\0';
    return a;
}
Run Code Online (Sandbox Code Playgroud)

请解释为什么m没有赋予desti这里的价值?

它将字符串副本的结果赋值给第三个变量

Ed *_*eal 6

  1. 你有内存泄漏.
  2. desti 将包含"dhawal"
  3. m将指向该字符串的空字符.这是与a结尾时相同的值str_cpy

为了避免这种用途

char *str_cpy(char *a,char *b)
{
    char *r=a;
    while(*b!='\0')
    {
        *a = *b;
        a++;
        b++;
    }
    *a = '\0';
    return r;
}
Run Code Online (Sandbox Code Playgroud)