Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在这种情况下如何使用malloc?_C - Fatal编程技术网

在这种情况下如何使用malloc?

在这种情况下如何使用malloc?,c,C,我是C的新手,所以请容忍我 我有一个函数来计算名为char strLength的字符串中的字符数,但我必须创建一个函数,该函数使用此函数来计算传递字符串中的字符数,为空终止符mallocate一个新字符串,复制该字符串,然后返回副本 以下是我所拥有的: 字符计数器 int strLength(char* toCount) { int count = 0; while(*toCount != '\0') { count++; toCount

我是C的新手,所以请容忍我

我有一个函数来计算名为
char strLength
的字符串中的字符数,但我必须创建一个函数,该函数使用此函数来计算传递字符串中的字符数,为空终止符mallocate一个新字符串,复制该字符串,然后返回副本

以下是我所拥有的:

字符计数器

int strLength(char* toCount)
{
    int count = 0;

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

    return count;
}
这是这个备受追捧的函数的开始

char* strCopy(char *s)
{
    int length = strLength(s);

}

由于您正在与
malloc
作斗争,下面是下一行的内容:

char* strCopy(char *s)
{
    int length = strLength(s);
    char *res = malloc(length+1);
    // Copy s into res; stop when you reach '\0'
    ...
    return res;
}

您需要
strdup
。然而,由于我怀疑这是一个学习练习:

char *strCopy(const char *src)
{
    size_t l = strlen(src) + 1;
    char *r = malloc(l);
    if (r)
       memcpy(r, src, l);
    return r;
}
如果您想知道如何自己复制字符串,可以使用以下内容替换
memcpy

char *dst = r;
while (*src)
   *dst++ = *src++;
*dst = 0;
但是我建议使用库函数:如果不是
strdup
,那么
malloc
+
memcpy

  • 您可以使用strdup()clib调用

  • 你可以这样写:

  • char *dst = r;
    while (*src)
       *dst++ = *src++;
    *dst = 0;
    

    我真的在为如何使用mallocI苦苦挣扎,我猜你没有在这个网站上的37000篇左右的帖子中看到过在C标签下包含关键字
    malloc
    @user3089390否,这将创建一个内存层。下一行应该是或。或者,您可以编写自己的循环进行复制。不要忘记将
    '\0'
    放在
    res
    的末尾。或者,很可能是您自己的自定义函数来复制字节(因为您必须实现
    strlen
    )。我不知道如何添加每个字符,我会将其视为数组吗?我觉得我应该尝试使用条件(*s!='\0')进行while循环,但我觉得这是错误的……strcpy和memcpy不能使用。我正在尝试编写自己的函数。@user3089390您可以通过将
    s
    res
    视为两个数组来添加每个字符。将零从
    s
    的最后一个位置复制到
    res
    后,您可以停止。我很感激,但是memcpy超出了我的知识范围