用VC编一个例子
#include "stdafx.h"int main(int argc, char* argv[])
{ int a[50];
printf("Array size: %d",sizeof(a));
return 0;
}发现结果是200(50*4)
但是以前学指针时,不是访问数组名就是访问数组首元素的地址吗?即 a <--> &a[0]
当时我理解的数组实现时就是指针.
所以我一直认为sizeof(a)=4而不是200
有点糊涂,请朋友们指点.
#include "stdafx.h"int main(int argc, char* argv[])
{ int a[50];
printf("Array size: %d",sizeof(a));
return 0;
}发现结果是200(50*4)
但是以前学指针时,不是访问数组名就是访问数组首元素的地址吗?即 a <--> &a[0]
当时我理解的数组实现时就是指针.
所以我一直认为sizeof(a)=4而不是200
有点糊涂,请朋友们指点.
// sizeof( array[0] ) is 4
而不是你的數組的大小.
ASSERT(sizeof(a)/sizeof(a[0]) == 50);
int a[50];//这时在堆栈中分配200字节
int *a=new int[50];//这时堆栈中只分配4字节。
sizeof是取堆栈中分配的字节数。
sizeof expressionThe 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.For related information, see Operators.Example// Example of the sizeof keyword
size_t i = sizeof( int ); struct align_depends {
char c;
int i;
};
size_t size = sizeof(align_depends); // The value of size depends on
// the value set with /Zp or
// #pragma packint array[] = { 1, 2, 3, 4, 5 }; // sizeof( array ) is 20
// sizeof( array[0] ) is 4
size_t sizearr = // Count of items in array
sizeof( array ) / sizeof( array[0] );
char *p = a;
cout<< sizeof(a) << endl; // 12字节
cout<< sizeof(p) << endl; // 4字节void Func(char a[100])
{
cout<< sizeof(a) << endl;// 4字节而不是100字节数组退化为指针
}
见高质量C++/C编程指南
up
换句话说,数组和指针是两个相互独立的类型。虽然大多数时候“数组名”表现为一个同类型的“指针”,但实际上数组和指针是不同的。他们的不同体现在内存的具体存储方式是不同的,也就是说编译器能区分出一个变量是数组类型的变量,而不是一个指针类型的变量。虽然你可以这样理解数组的用法,但编译器从来没有把数组看成是一种特殊的指针。sizeof是一个和类型紧密相关的函数,所以他返回数组的大小而不是指针的大小就不足为怪了。
sizeof(&a[0])的区别。前者是数组a的长,后者是a[0]的长。
a表示整个数组地址的开始,&a[0]表示数组第一列的开始,数值上一样,
概念上不一样。
1. 虽然我们总将a[50]的a视为指针, 但编译器则不这么认为. 我们只是为了方便理解才这么认为. 因为,首先编译器决不会再为"指针a"分配内存,而只为a[50]分配50个相应类型的内存, 这个时候还可以认为a只是一个内存里程序代码的行号, 编译器认得, 但a这个"指针"本身不占用任何内存.
但是如果定义int* a; 那就不同了,编译器必须得为a分配4字节的内存,同时也可以将a看作汇编程序代码的行号,但该行有4字节的内存.
2. sizeof()函数仅计算在栈里分配的内存,而不计算在堆里分配的内存, 你为int* a = new int[50];在堆里分配了50*4个字节,但事实上,编译器还在栈里为指针a分配了4字节内存, 所以sizeof(a)返回4, 而int a[50]编译器只在栈里分配50*4个字节的内存, 所以sizeof(a)返回50*4
今天试了一下,果如hnyyy(前进) ( ) 所言:
作为函数参数时是sizeof确实是作为指针处理的,颇为疑惑。
终在C++ Primer(中文版),找到关于数组作为函数参数的说明。
大意如下:
1.数组在作为函数参数时总是被当作指针处理。即int a[]与int a[100]等价,此时编译器不检查数组长度。
2.指针的sizeof总返回指针的长度而不是所指对象的长度。
3.引用的sizeof总返回对象的长度。
4.要想返回函数参数的实际大小,在参数说明时应声明成引用。即int (&a)[100].大致如此,详见C++ Primer 7.3.3数组参数部分和前面有关sizeof的说明。