strcpy using pointers

前端 未结 7 1071
无人及你
无人及你 2021-01-13 11:29

I\'m trying to write strcpy on my own using pointers and I get an error during runtime.

void str_cpy(char **destination, const char *source) {
//    char *s1         


        
7条回答
  •  一向
    一向 (楼主)
    2021-01-13 12:29

    No, it's not okay. Why? Because str is a NULL pointer. It's pointing to nothing. When you try to write values into it, where will they go? It's not pointing to any allocated memory!

    You first have to allocate memory for str. You can do:

    char *str = malloc(strlen("String") + 1); // + 1 for the '\0' character at the end of C-style strings
    

    Or you can do:

    char str[256]; // make str large enough to hold 256 chars. Note that this is not as safe as the above version!
    

    Also, destination should be a single pointer, not a double pointer. Well, it's not technically wrong to use a double pointer, it's just unnecessary.

    Optionally, you can allocate the memory in the str_cpy function, like so:

    void str_cpy(char **destination, const char *source) {
        *destination = malloc(strlen(source) + 1);
        // ... continue as normal
    

提交回复
热议问题