char *strcpy(char* d, const char *s)函数的功能是将把从s地址开始且含有 ‘ \0 ’ 结束符的字符串复制到以d开始的空间。
运行下面这段代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
char *a = "aa";
char s[] = "123456789";
char d[] = "123";
strcpy(d,s);
cout<<"d:"<<d<<endl;
cout<<"s:"<<s<<endl;
cout<<&a<<endl;
cout<<&s<<endl;
cout<<&d<<endl;
return 0;
}
运行结果如下(其中地址大小每次执行可能不同):
发现d的打印结果是123456789, s的打印结果是56789
这是因为d , s的内存地址是相邻的,内存中(从0x28fefe ~ 0x28ff02 )是这样排列的 :1 2 3 \0 1 2 3 4 5 6 7 8 9 \0,
当执行strcpy(d , s)时,s的长度为10,所以内存中排列顺序变为: 1 2 3 4 5 6 7 8 9 \0 7 8 9 \0
此时打印d, 打印的是d的地址到\0之间的字符,所以打印得到d: 123456789,
打印s,类似打印的是s的地址到\0之间的字符,对比位置发现s的地址对应的字符是 5 ,所以打印出的结果 s: 56789