strcpy使用指针

ori*_*han 3 c

我正在尝试使用指针自己编写strcpy,我在运行时遇到错误.

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

   while (*source != '\0') {
      **destination++ = *source++; //Get an error here
   }
   **destination = '\0';
}
Run Code Online (Sandbox Code Playgroud)

我把这个函数调用如下:

char *str = NULL;
str_cpy(&str, "String");
Run Code Online (Sandbox Code Playgroud)

不行吗?

谢谢!

Cor*_*lks 6

不,这不好.为什么?因为str是一个NULL指针.它没有指向任何东西.当你尝试将值写入其中时,它们会去哪里?它没有指向任何已分配的内存!

首先必须为内存分配str.你可以做:

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

或者你可以这样做:

char str[256]; // make str large enough to hold 256 chars. Note that this is not as safe as the above version!
Run Code Online (Sandbox Code Playgroud)

此外,destination应该是单个指针,而不是双指针.嗯,使用双指针在技术上并不是错误的,这是不必要的.

或者,您可以在str_cpy函数中分配内存,如下所示:

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