数组那些不为菜鸟所知的秘密(零)

来源:互联网 发布:社会关系网络企业 编辑:程序博客网 时间:2024/05/01 17:55

1、数组名的本质

数组名的本质相当于一个常量指针
如:int a[10] a<=>int *const a;
int b[10][20] b<=>int (*const b)[20]
所以a[5]==*(a+5);
b[8][9]==((b+8)+9)==*(b+8)[9];
2、数组在函数中传参时会被降级为指针
3、数组大小

int a[10]={0};int b[10]={1,2,3,4,5,6};a=b;

要想把b的内容赋给a,必须按照元素逐个赋值,或者使用内存拷贝函数memcpy().
在声明数组时,一般有一下3中方式:
(1)明确的指出他的元素个数,编译器会按照给定的元素个数来分配储存空间。
(2)不指定元素个数直接初始化,编译器会根据你提供的初始值的个数来确定数组的元素个数。
(3)同时指定元素个数并进行初始化,但是不允许既不指定元素个数,又不初始化,因为编译器
也不知道应该为数组分配多少空间。
编译器再给数组分配空间时总是以用户指定的元素个数为准,如果初始值得个数多于指定个数则
报错,若用户没有指定个数,则编译器计算初始值的个数作为数组的元素个数;如果初始值个数
小于指定的数组元素个数,则后面的元素全部初始化为0
二维数组
二维数组在c/c++中都是按行序优先来储存的

动态创建初始化和删除数组的方法

一位数组的创建与删除

char *p=new char[1025];delete[]p;//正确delete p//错误

多为数组的创建与删除

char *p1=new char[5][3];//错误char (*p2)[3]=new char[5][3];//退化成一维数组指针正确delete []p2//正确delete [][]p2//错误

代码示例:

#include<iostream>#include<string.h>using namespace std;int main(){    char *str = "hello";    char str1[5] = { 'h', 'e', 'l', 'l', 'o' };    char str2[6] = { 'h', 'e', 'l', 'l', 'o' };//字符不够会自动补'\0';    cout << sizeof(str) << endl;//4 指针大小    cout << strlen(str) << endl;//5,strlen 遇到'\0'截止    cout << sizeof(str1) << endl;//5    cout << strlen(str1) << endl;//后面没有/0结尾,随机数    char str3[] = { 'h', 'e', 'l', 'l', 'o' };    cout << str3 << endl;    cout << strlen(str3) << endl;//str3结果同str1因为不加数字也不会自动加\0    cout << sizeof(str2) << endl;//6sizeof求所占空间的字节数    cout << strlen(str2) << endl;//5字符不够会自动补‘\0’    cout << str1 << endl;//hello烫烫。。没有结束符\0    system("pause");}

c++只有在delete后面加[]时才会去某个特定的位置查找数组的大小信息,否则他只山粗一个对象。

#include<iostream>using namespace std;int main(){    int arr[] = { 1, 2, 3, 4 };    int *ptr = (int *)(&arr + 1);//ptr指向数组后的一个一片四字节空间    cout << *(arr + 1) << endl;//2此时的arr代表数组首元素的首地址    cout << *(ptr - 1) << endl;//4,&arr代表整个数组的首地址    cout << sizeof(arr[100]) << endl;//arr[100]不会出错,因为sizeof是关键字,求值是在编译的时候所以不会出错    //&arr与&arr[0]代表不同的含义,&arr整个数组的首地址,&arr[0]数组首元素的地址    cout << &arr[0] << endl;//0100FCB0    cout << &arr[1] << endl; //0100FCB4数组的元素a[0]在低地址, a[n]在高地址    cout << sizeof(arr) << endl;//16    int brr[2][3] = { { 1, 2, 3 }, { 3, 4 } };    cout << sizeof(brr) << endl;//24相当于整个数组的大小    cout << brr << endl;//0048FA5C    cout << sizeof(*brr) << endl;//12相当于一位数组brr[3]的大小    cout << *brr << endl;//0048FA5C    cout << sizeof(&brr) << endl;//4普通指针的大小    cout << &brr << endl;//0048FA5C    cout << sizeof(&brr[0]) << endl;//4    cout << &brr[0] << endl;//0048FA5C    cout << sizeof(&brr[0][0]) << endl;;//4    cout << &brr[0][0] << endl;//0048FA5C    cout << sizeof(brr[0]) << endl;//12相当于一位数组brr[3]的大小    cout << brr[0] << endl;//0048FA5C    system("pause");

}

2 0
原创粉丝点击