-3

我必须总是做我的功能。我不能使用标准库。

My_cpy , my_len 和 my_strdup 函数在这里。请帮我检查一下。我认为这很容易,但我对此功能有疑问。我在页面末尾显示了错误。我认为这很清楚。另外这是C++

非常感谢。

代码:

void my_cpy(char* dest, const char* src) {

    int i = 0;
    while (src[i] != '\0') {
        dest[i] = src[i];
        i++;
    }
    dest[i] = '\0';
}

int my_len(const char* p) {

    int c = 0;
    while (*p != '\0')
    {
        c++;
        *p++;
    }
    return c;
}

char *my_strdup(const char *s) {
    char* d = malloc(my_len(s) + 1);    // Space for length + null
    if (d == NULL) return NULL;         //No memory
    my_cpy(d, s);                       // Copy the characters
    return d;                           // Return the new string
}

我对此功能有错误。我怎么解决这个问题?

错误(活动)“void *”类型的值不能用于初始化“char *”类型的实体

`Error    C2440   'initializing': cannot convert from 'void *' to 'char *'`

我写的:

char* d = (char*) malloc(my_len(s) + 1)

但现在 p 上的问题。始终为 NULL。

4

1 回答 1

0

malloc()是返回void *类型。在 C 中不需要强制转换,但在 C++ 中需要显式强制转换:

char* d = static_cast<char*>(malloc(my_len(s) + 1));

(更喜欢static_castC 风格的演员表)

你也可以使用

char* d = new[my_len(s) + 1];

但在这种情况下,您需要确保函数的客户端不会调用free()but delete[]

于 2017-01-03T15:01:19.430 回答