问题描述
首先,这是一些代码:
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
所指向的数组的大小(而不是仅仅给出其大小,在32位系统上为4个字节)?
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 on a 32-bit system)?
推荐答案
不,您不能.编译器不知道指针指向什么.有一些技巧,例如以一个已知的带外值结束数组,然后计算大小直到该值,但这并不使用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()
.
另一种技巧是 Zan 所提到的,它可以将大小存储在某个地方.例如,如果要动态分配数组,请分配一个比所需块大一个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"(指向数组的指针)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!