Value of type error in C++ function always NULL

355 views Asked by At

i have to do my function always.I can not using standart library.

My_cpy , my_len and my_strdup function in here. Please check it for me. I think it is easy but i have a problem about this function. I showed the error at the end of the page. I think it is clear. In addition this is C++

Thanks a lot.

Codes:

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
}

I have error on this functions. How can i solve this problem?

Error (active) a value of type "void *" cannot be used to initialize an entity of type "char *"

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

I wrote it:

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

but now problem on p . Always NULL.

1

There are 1 answers

4
EmDroid On

malloc() is returning void * type. In C it does not need to be cast, but in C++ it needs to be cast explicitly:

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

(prefer static_cast to a C-style cast)

You can also use

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

But in that case you need to make sure that the client of the function will not call free() but delete[].