在练习数据结构过程中,定义指针p,并且申请了10个char类型空间,但在计算p所指空间大小时候,发现了一些奇怪的现象。
- #include
- #include
-
- int main(){
- char s[12];
- printf("the size of memory occupied = %d\n",sizeof(s));//12
-
- char *s1 = "hello,world.";
- printf("the size of memory occupied = %d\n",sizeof(s1));//8
-
- char *s2 = (char *)malloc(sizeof(char) * 12);
- printf("the size of memory occupied = %d\n",sizeof(s2));//8
-
- int a[3] = {1,2,3};
- printf("the size of memory occupied = %d\n",sizeof(a));//12
-
- int *a1 = (int *)malloc(sizeof(int)*3);
- printf("the size of memory occupied = %d\n",sizeof(a1));//8
-
- return 0;
- }
可以发现,sizeof()只有在计算定义为数组的大小是准确的,在计算指针指向的数组或者申请空间的大小时候,不准确。
通过查阅资料得知,sizeof()不可以用来计算申请出来空间的大小。
那么,为什么是8?是因为8是指针所占空间的大小。
那我想要计算申请的空间的大小,怎么办?
=========> _msize() <=============
_msize()函数可以计算出申请空间的大小,如下:
- #include
- #include
-
- int main(){
- char *s2 = (char *)malloc(sizeof(char) * 12);
- printf("sizeof(s2) = %d\n",sizeof(s2));//8
- printf("_msize(s2) = %d\n",_msize(s2));//12
-
-
- int *a1 = (int *)malloc(sizeof(int)*3);
- printf("sizeof(a1) = %d\n",sizeof(a1));//8
- printf("_msize(a1) = %d\n",_msize(a1));//12
-
- return 0;
- }
!!!!!!!!!!!!如下两位博主讲的更为详细!!!!!!!!!!!!!!!!!!
参考资料:
C++学习笔记之如何获取指针开辟空间或数组空间的大小以及_countof、sizeof、strlen、_Msize的区别