如何找到“sizeof"(指向数组的指针)? [英] How to find the 'sizeof' (a pointer pointing to an array)?

查看:23
本文介绍了如何找到“sizeof"(指向数组的指针)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,这是一些代码:

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 位系统上是四个字节)?

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"(指向数组的指针)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆