问题描述
首先,这里是一些code:
First off, here is some code:
int main()
{
int days[] = {1,2,3,4,5};
int *ptr = days;
printf("%u\n", sizeof(days));
printf("%u\n", sizeof(ptr));
return 0;
}
有没有办法找出数组的大小 PTR
指向(而不是只给它的大小,这是四个字节)?
Is there a way to find out the size of the array that ptr
is pointing to (instead of just giving its size, which is four bytes)?
推荐答案
没有,你不能。编译器不知道指针指向。有花样,像结束与已知的外的带外值的数组,然后计数大小直到该值,但是这不使用的sizeof。
No, you can't. The compiler doesn't know what the pointer is pointing to. There are tricks, like ending the array with a known out-of-band value and then counting the size up until that value, but that's not using sizeof.
另一个窍门是由,这是某处藏匿大小提到的。例如,如果你是动态分配的数组,分配块的一个INT比你需要一个更大,藏匿在第一INT的大小,并返回PTR + 1的指针数组。当你需要的大小,减小在藏匿价值的指针和偷看。只记得释放整个街区从头开始,而不仅仅是数组。
Another trick is the one mentioned by Zan, which is to stash the size somewhere. For example, if you're dynamically allocating the array, allocate a block one int bigger than the one you need, stash the size in the first int, and return ptr+1 as the pointer to the array. When you need the size, decrement the pointer and peek at the stashed value. Just remember to free the whole block starting from the beginning, and not just the array.
这篇关于如何找到“的sizeof”(一个指针指向一个数组)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!