是否可以在 strcpy 中创建字符数组?

Con*_*nor 2 c memory string initialization strcpy

是否可以使用 C 复制字符串strcpy而不先将内存分配给 a char *character_array

基本上,是这样的可能:

strcpy(char *my_string, another_string);
Run Code Online (Sandbox Code Playgroud)

其中my_string成为与 具有相同长度和内容的初始化字符串another_string

Ste*_*mit 5

strcpy从不分配内存。目标必须是指向足够的、可写的、有效分配的内存的指针,并且有责任确保目标内存已有效分配、足够长且可写。

所以这些都可以:

char *another_string = "hello";
char my_string_1[20];
strcpy(my_string_1, another_string);     /* valid (plenty of space) */

char my_string_2[6];
strcpy(my_string_2, another_string);     /* valid (just enough space) */

char my_string_3[] = "world";
strcpy(my_string_2, another_string);     /* valid (just enough space) */

char buf[6];
char *my_string_4 = buf;
strcpy(my_string_4, another_string);     /* valid (via intermediate pointer) */

char *my_string_5 = malloc(6);
strcpy(my_string_5, another_string);     /* valid (assuming malloc succeeds) */

char *my_string_6 = malloc(strlen(another_string) + 1);
strcpy(my_string_6, another_string);     /* valid (assuming malloc succeeds) */
Run Code Online (Sandbox Code Playgroud)

但这些都是无效的:

char my_string_7[5];
strcpy(my_string_7, another_string);     /* INVALID (not enough space) */

char *my_string_8 = "world";
strcpy(my_string_8, another_string);     /* INVALID (destination not writable) */

char *my_string_9;
strcpy(my_string_9, another_string);     /* INVALID (destination not allocated) */

char *my_string_10 = malloc(20);
free(my_string_10);
strcpy(my_string_10, another_string);    /* INVALID (no longer allocated) */

char *exceptionally_bad_allocator()
{
    char local_buffer[20];
    return local_buffer;
}

char *my_string_11 = exceptionally_bad_allocator();
strcpy(my_string_11, another_string);    /* INVALID (not validly allocated) */
Run Code Online (Sandbox Code Playgroud)