Can I copy a string in an empty string?

后端 未结 3 698
温柔的废话
温柔的废话 2021-01-25 13:31

Suppose I do like this to copy the string.

char str[] = \"\";
char *str2 = \"abc\";
strcpy(str, str2);
printf(\"%s\", str);  // \"abc\"
printf(\"%d\", strlen(str         


        
3条回答
  •  情深已故
    2021-01-25 13:40

    You are writing past the memory space allocated to str on the stack. You need to make sure you have the correct amount of space for str. In the example you mentioned, you need space for a, b, and c plus a null character to end the string, so this code should work:

    char str[4];
    char *str2 = "abc";
    strcpy(str, str2);
    printf("%s", str);  // "abc"
    printf("%d", strlen(str));  // 3
    

提交回复
热议问题