# strcpy 演示 ```c #include <stdio.h> #include <string.h> int main(int argc, char const *argv[]) { char *s = "11111"; char *d; strcpy(d,s); printf("%s\n", *d); return 0; } ``` 编译运行 ``` Segmentation fault: 11 ``` # 为什么呢? 因为`d`在初始化的时候没有申请内存;默认只是分配了字符串首地址(指针),通过下面的程序可以看到 ```c #include <stdio.h> #include <string.h> int main(int argc, char const *argv[]) { char *s = "123456789"; char *d; printf("%p\n", &d); printf("sizeof(d) is: %lu\n",sizeof(d)); strcpy(d,s); printf("%s\n", d); return 0; } ``` ```shell 0x7fff5a2c7ad0 sizeof(d) is: 8 Segmentation fault: 11 ``` 要想程序运行没有意外,那么就应该提前给字符串申请一块内存,足够存放这些字符。 上面的例子中是1~9的数字,再加上末尾的`\0`所以,需要10个字节,那么我们需要申请至少10个字节的空间。 ```c #include <stdio.h> #include <string.h> int main(int argc, char const *argv[]) { char *s = "123456789"; char *d; printf("%p\n", &d); char buff[10] = {0}; d = buff; printf("%p\n", &d); printf("%p\n", &buff); printf("%p\n", d); strcpy(d,s); printf("%s\n", d); return 0; } ``` ```javascript 0x7fff5fbff768 0x7fff5fbff768 // 赋值之后,d的指针地址不变 0x7fff5fbff78e 0x7fff5fbff78e // d 里面存放的值就是 buff 的指针地址 123456789 ```