1. 程式人生 > >C++中char型別陣列的長度問題

C++中char型別陣列的長度問題


char* a =new char[30];
	cout<<"未初始化char陣列--sizeof = "<<sizeof(a)<< endl;
	cout<<"未初始化char陣列--strlen = "<<strlen(a)<< endl;
	cout<<"**************************"<<endl;
	char* b = "hello";
	cout<<"hello 陣列--sizeof = "<<sizeof(b)<< endl;
	cout<<"hello 陣列--strlen = "<<strlen(b)<< endl;
	cout<<"**************************"<<endl;
	char* c;
	cout<<"char陣列指標--sizeof = "<<sizeof(c)<< endl;
	//cout<<"char陣列指標--strlen = "<<strlen(c)<< endl;  編譯通過,執行出錯
	cout<<"**************************"<<endl;
	char* d =new char[30];
	d = "hello";
	cout<<"為已開闢空間的陣列賦值--sizeof = "<<sizeof(d)<< endl;
	cout<<"為已開闢空間的陣列賦值--strlen = "<<strlen(d)<< endl;
	cout<<"**************************"<<endl;
	char* e =new char[30];
	e[0] = 'h'; e[1] = 'e';e[2] = 'l';e[3] = 'l';e[4] = 'o';e[5] = '\0';
	cout<<"hello 陣列 分配的記憶體未填滿,且加\0--sizeof = "<<sizeof(e)<< endl;
	cout<<"hello 陣列 分配的記憶體未填滿,且加\0--strlen = "<<strlen(e)<< endl;
	cout<<"**************************"<<endl;
	char* ee =new char[30];
	ee[0] = 'h'; ee[1] = 'e';ee[2] = 'l';ee[3] = 'l';ee[4] = 'o';ee[5] = '\0';
	ee[6] = '\0';
	cout<<"兩個\\0的char陣列--sizeof = "<<sizeof(ee)<< endl;
	cout<<"兩個\\0的char陣列--strlen = "<<strlen(ee)<<endl;
	cout<<"**************************"<<endl;
	char* eee =new char[30];
	eee[0] = 'h'; eee[1] = 'e';eee[2] = 'l';eee[3] = 'l';eee[4] = 'o';
	cout<<"未手動新增\\0的char陣列--sizeof = "<<sizeof(eee)<< endl;
	cout<<"未手動新增\\0的char陣列--strlen = "<<strlen(eee)<<endl;
	cout<<"**************************"<<endl;
	char* eeee =new char[30];
	for(int i =0;i<30;i++)
	{
		eeee[i] ='h';
	}
	cout<<"陣列分配記憶體填滿,未加\\0--sizeof = "<<sizeof(eeee)<< endl;
	cout<<"陣列分配記憶體填滿,未加\\0--strlen = "<<strlen(eeee)<< endl;
	cout<<"**************************"<<endl;
	char* eeeee =new char[30];
	for(int i =0;i<29;i++)
	{
		eeeee[i] ='h';
	}
	cout<<"陣列分配記憶體填滿,加\\0--sizeof = "<<sizeof(eeeee)<< endl;
	cout<<"陣列分配記憶體填滿,加\\0--strlen = "<<strlen(eeeee)<< endl;
	cout<<"**************************"<<endl;
	string s("hello");
	cout<<"hello string--sizeof = "<<sizeof(s)<< endl;
	cout<<"hello string--strlen = "<<strlen(s.c_str())<< endl;