如何确定一个分配的C缓冲区的大小? [英] How to determine the size of an allocated C buffer?

查看:552
本文介绍了如何确定一个分配的C缓冲区的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个缓冲区,并想要做一个测试看是否缓冲区具有足够的容量,即找到的元素个数,我可以添加到缓冲区。

I have a buffer and want to do a test to see if the buffer has sufficient capacity I.e. find number of elements I can add to the buffer.

char *buffer = (char *)malloc(sizeof(char) * 10);

做一个

int numElements = sizeof(buffer); 

不返回10,我如何能做到这一点任何想法?

does not return 10, any ideas on how I can accomplish this?

推荐答案

缓存只是没有大小信息的指针。然而,的malloc()例程将持有分配的大小你做,所以当你免费的(),它释放的空间适量。所以,除非你想在malloc()函数的功能潜水,我建议你刚刚保存的分配自己的大小。 (为一个可能的实施方案,请参阅其他的API回答的例子)。

buffer is just a pointer without size information. However the malloc() routine will hold the size of the allocation you made so when you free() it, it frees the right amount of space. So unless you want to dive in the malloc() functionality, I recommend you just save the size of the allocation yourself. (for a possible implementation, see the example in the other API answer).

这篇关于如何确定一个分配的C缓冲区的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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