深入理解C語言sizeof()計算空間大小為8的問題
在練習數(shù)據(jù)結構過程中,定義指針p,并且申請了10個char類型空間,但在計算p所指空間大小時候,發(fā)現(xiàn)了一些奇怪的現(xiàn)象。
#include <stdio.h> #include <stdlib.h> 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; }
可以發(fā)現(xiàn),sizeof()只有在計算定義為數(shù)組的大小是準確的,在計算指針指向的數(shù)組或者申請空間的大小時候,不準確。
通過查閱資料得知,sizeof()不可以用來計算申請出來空間的大小。
那么,為什么是8?是因為8是指針所占空間的大小。
那我想要計算申請的空間的大小,怎么辦?
=========> _msize() <=============
_msize()函數(shù)可以計算出申請空間的大小,如下:
#include <stdio.h> #include <stdlib.h> 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語言——判斷矩陣維數(shù)(sizeof、_msize)
C++學習筆記之如何獲取指針開辟空間或數(shù)組空間的大小以及_countof、sizeof、strlen、_Msize的區(qū)別
到此這篇關于深入理解C語言sizeof()計算空間大小為8的問題的文章就介紹到這了,更多相關C語言sizeof()計算空間大小內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++11中內聯(lián)函數(shù)(inline)用法實例
內聯(lián)函數(shù)本質還是一個函數(shù),但在聲明的時候,函數(shù)體要和聲明結合在一起,否則編譯器將它作為普通函數(shù)來對待,下面這篇文章主要給大家介紹了關于C++11中內聯(lián)函數(shù)(inline)的相關資料,需要的朋友可以參考下2022-10-10