c++ 的编译很严格
如果定义一个数组的大小的,如果未能指定的大小是const 类型的,或要到运行才知道的,则会编译失败,这点和java不一样
example:
int size =3;
chat cbuf[size]; 失败
const int size =3 + 1;
chat cbuf[size]; 失败
如果为
const int size =3;
chat cbuf[size]; 成功
显式初始化
int ai[3] = {1,2}; // 未够的默认为0,长度为3
int ai[] = {1,2} ; // 长度为2
字符数组的特别
chat ca1[] = {'c','+','+'}; 没有null(\0)
chat ca2[] = {'c','+','+','\0'}; 有null
chat ca3[] = "c++"; 和ca2是一样的,长度待测试
chat ca4[3] = "c++" ;出错
c 风格字符串
char * aa = "sdfasdf";
char * bb = ca1;
while(*aa)
++aa
这个必须是aa 读到为null才会停止,如果该字符有问题,则是读到内存某处为null才会停止
string.h是c标准提供的,尽量使用C++ string
常用字符串方法
strlen(s); 返回s的长度,不包括null
strcmp(s1,s2); 比较是否相等,相等返回0,否负数 ,这个是比较内容,如java 里的equals()
strncat(s1,s2); 将s2连接到s1,并返回s1
strncpy(s1,s2,n); 将s2的前n个复制给s1,并返回s1
不允许数组直接复制和赋值
example
int a[] ={1,2,3};
int b[](a);// error
int c[3];
c = a; //error
指针数据,返回的为数组的首地址
int a[] = new int[2]; // 创建未初始化
int a[] = new int[2](); // 创建初始化0
string s [] = new string[2]; 创建初始化null
string s * = new string[2](); 创建初始化null
int *a = new int[2]; // 创建未初始化
int *a = new int[2](); // 创建初始化0
const int *a = new const int[2]; //error ,还未初始化,不能const
const int *a = new const int[2](); //ok
允许动态分配空数据
int *a = new int[n]; //ok
int *a = new int[n](); // error
定义就不行了,一定要知道n为const
int a[n];// error
分配(new)的大小可以为0,但定义不行
chat a[0];//error
chat *a= new chat[0] ; // ok
最后注意的问题是释放
delete [] 指针;
delete [] a; 不能缺少了[]
有空再续...