1.一个strcpy()函数引发的思考:
#include<iostream>
using namespace std;
struct name_connfd{
char *name;
int connfd;
char c;
double d;
};
int main(){
struct name_connfd st;
st.name="zcx";
st.connfd=5;
cout<<sizeof(st)<<endl; //ouput 24, VC下的struct变量地址的对齐处理
char buf[5]="zcx";
char *p="xw";
char p3[5];
char *p2=new char[5];
cout<<p<<' '<<*p<<' '<<(void*)p<<' '<<&("xw")<<' '<<&p<<' '<<sizeof(p)<<' '<<sizeof(p3)<<endl;//output xw x 00877830 00877830 0012FC74 4 5
//上面的输出分别为整个字符串,首个字符,p指向的字符串的地址(即p中存储的值),常量"zcx"的地址,指针p所在地址,p的大小(32位机为4),pl的内存大小
//像char *p或者char *p="zcx"这样,系统只为p分配了p的内存(存放p中的地址,32位机就是4字节),而字符数组则分配了其数组中将要存放的元素的所有所需内存
//strcpy(p,buf); //编译出现warning 运行出错,并没有给p分配有效的内存空间
strcpy(p2,buf);//正确,但VS2010下会出现warning,strcpy不安全的函数就像gets()一样,可以使用strcpy_s和strncpy代替
strcpy(p3,buf); //正确,有warning
return 0;
}