int data[9]={1,2,3,4,5,6,7,8,9};
int * pData =data;
if(*pData == *data)
cout<< " *pData = *data";// 是相同的
if(pData == data)
cout<<endl<< "pData = data";// 是相同的
cout<<endl<<"int 指针 和 int 数组 ,sizeof计算方式是不同的. 虽然他们存的是相同的地址"; 当sizeof 计算 int * 和 Int [] 数组时 是两种方式。
cout<< sizeof(pData);// 输出 4
cout<< sizeof(data);// 输出 36
sizeof Operator
sizeof expression
The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type
(including aggregate types). This keyword returns a value of type size_t.
The expression is either an identifier or a type-cast expression (a type specifier enclosed in
parentheses).
When applied to a structure type or variable, sizeof returns the actual size, which may include
padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof
returns the size of the entire array. The sizeof operator cannot return the size of dynamically
allocated arrays or external arrays.
sizeof使用场合。
- 1.sizeof操作符的一个主要用途是与存储分配和I/O系统那样的例程进行通信。例如:
· void *malloc(size_t size),
· size_t fread(void * ptr,size_t size,size_t nmemb,FILE * stream)。
- 2.用它可以看看一类型的对象在内存中所占的单元字节。
· void * memset(void * s,int c,sizeof(s))
- 3.在动态分配一对象时,可以让系统知道要分配多少内存。
- 4.便于一些类型的扩充,在windows中就有很多结构内型就有一个专用的字段是用来放该类型的字节大小。
- 5.由于操作数的字节数在实现时可能出现变化,建议在涉及到操作数字节大小时用sizeof来代替常量计算。
- 6.如果操作数是函数中的数组形参或函数类型的形参,sizeof给出其指针的大小。