# 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
```