仅使用返回的指针获取 malloc 的大小 [英] Getting the size of a malloc only with the returned pointer

查看:34
本文介绍了仅使用返回的指针获取 malloc 的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够改变数组的大小,所以我以这种方式创建了一个:

I want to be able to vary the size of my array so I create one this way:

int* array;
array = malloc(sizeof(int)*10);//10 integer elements

我可以像往常一样使用它作为数组,但是当我尝试像这样找到它的大小时:

I can use this like an array as you normally would, however when I try to find the size of it like so:

size = sizeof(array)/sizeof(int);

我得到了答案 1,因为它没有将它识别为指向数组

I get the answer 1 because its not recognizing it as pointing to an array

如何获取数组的大小?(我知道它在技术上不是一个数组,但有没有办法计算分配的内存块的整个大小?)

How can I get the size of the array ? (I know its not technically an array but is there a way to work out the whole size of the allocated memory block ?)

我是否也正确地假设了我在描述中所说的内容?如果我在技术上有错误,请纠正我.

Also am I right in assuming what I have stated in the description ? If I am technically wrong about something please correct me.

推荐答案

指针一个指针,而不是一个数组.它永远不能被识别为数组",因为它不是数组.

The pointer is a pointer, and not an array. It can never be "recognized as an array", because it is not an array.

记住数组的大小完全取决于.

It is entirely up to you to remember the size of the array.

例如:

struct i_must_remember_the_size
{
    size_t len;
    int * arr;
};

struct i_must_remember_the_size a = { 10, NULL };
a.arr = malloc(a.len * sizeof *a.arr);

这篇关于仅使用返回的指针获取 malloc 的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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