2012-07-23 55 views
-2

可能重複:
determine size of dynamically allocated memory in cÇ - 這是由realloc的創建數組的大小

我在我的C代碼struct,但這個問題也同樣適用於所有其他類型,所以我會用int而不是我創建的struct

int *a = realloc(NULL, 10*sizeof(int)); 
printf("%d\n",sizeof(a)); //prints 4, needed to be 40 

int b[10]; 
printf("%d\n",sizeof(b)); //prints 40 

我的問題是這樣的:我用我的代碼realloc,我不知道我怎樣才能找到我的陣列的總大小。什麼是最簡單的方法來做到這一點?謝謝。

+0

'sizeof'不能做你想要的指針。你可以簡單地不「忘記」你傳遞給'realloc'的東西。 – cnicutar 2012-07-23 10:11:26

+0

@PaulR編譯時間?那麼'VLAs'呢? – cnicutar 2012-07-23 10:12:09

回答

1

請記住,sizeof是在編譯時進行評估(VLA除外,但它不是你的情況)。假設你以用戶的輸入作爲參數realloc的大小:編譯器不可能知道實際分配的大小。所以它返回指針的大小。

+0

「在編譯時評估」 - 對於C99來說顯然不是這樣,其中sizeof在運行時與VLA一起工作(今天我學到了一些新東西!)。 – 2012-07-23 10:16:03

+0

我明白了。那麼是否有任何函數可以動態計算其大小,還是應該將其大小保持在變量中? – ibrahim 2012-07-23 10:17:11

+0

您需要自己跟蹤分配大小 - 事實之後沒有便捷的方式獲取這些信息。 – 2012-07-23 10:19:53

0

總之,這是你需要存儲在代碼中的東西,並傳遞給你的各種功能。由於您已將該信息傳遞到realloc已可用。

還要記住,sizeof不會在指針上工作,它只會返回指針的大小,而不是指針指向的內存大小。

0

http://en.wikipedia.org/wiki/Sizeof

In the programming languages C and C++, the unary operator sizeof 
is used to calculate the size of any datatype, measured in the 
number of bytes required to represent the type. 

這意味着,你的架構指針這個

sizeof(int*) 

收益的大小。如果你想知道你的數組的大小,你所要做的:

sizeof(your_type) * array_size 
0

sizeof(a)返回指針的大小不是它指向。如果您使用mallocrealloc分配內存,則必須自行跟蹤。