您的位置:首页 > 编程语言 > C语言/C++

读《C++ Primer 第四版》再温C++ —— Chapter 4数组和指针

2014-06-27 16:00 417 查看
没有所有元素都是引用的数组。(数组类型不能为引用类型)

数组 - 容器
指针 - 迭代器
指针是用于数组的迭代器。

void *指针可以保存任何对象的地址。但是不能操作对象。
string str[] = "hello world";
void *p = str;    //ok
printf("*p =%c\n", *p);    //error
printf("*p =%c\n", *(char*)p); //ok


两个指针减法操作的结果是标准库类型(library type)ptrdiff_t. (是一个signed类型。size_t是unsigned类型,记得吗?)

typedef和const
typedef string* pstring;
const pstring pstr; //等价于 string * const pstr; 而不是 const string *pstr;


new动态创建长度为0的数组是合法的,返回有效的非0指针,但是对指针进行解引用是错误的。
char *cp = new char[0];    //ok


对于该指针,调用delete []cp进行内存释放,不会报错。不调用delete,也不会造成内存泄漏。(Unbuntu12.04测试)

混合使用标准类库string和C风格字符串
string str;
char *pstr = str;  //error
char *pstr = str.c_str();    //almost ok, but not quite
const char *pstr = str.c_str();    //ok


c_str返回的数组并不保证一定是有效的,接下来对string对象str的操作有可能会改变str的值,是刚才的返回的数组失效。如果程序员确实需要持续访问该数据,则应该复制str.c_str()返回的数组。

多维数组
int ia[3][4]; // 最右边的是第一维,以此类推。[4]是第1维,[3]是第2维

初始化
int ia[3][4] = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11}
};


等价于
int ia[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};


int ia[3][4] = {{0}, {4}, {8}};


等价于

int ia[3][4] = {
{0, 0, 0, 0},
{4, 0, 0, 0},
{8, 0, 0, 0}
};


int ia[3][4] = {0, 1, 2, 3};


等价于

int ia[3][4] = {
{0, 1, 2, 3},
{0, 0, 0, 0},
{0, 0, 0, 0}
};


数组的指针
int (*ip)[4];    //一个指向大小为4的一维int数组

int ia1[4] = {1, 2, 3, 4};
ip = &ia[0];    //ok

int ia2[3] = {1, 2, 3};
ip = &ia2[0];    //error


typedef简化数组的指针的定义
typedef int int_array[4];    //int_array类型为int[4]数组
int_array *p;


注意:
int *ip[4];   //ip是一个int *[4]数组,不是数组指针
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: