获取一个malloc的大小只与返回的指针 [英] Getting the size of a malloc only with the returned pointer

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

问题描述

我希望能够让我创建一​​个这样的改变我的数组的大小:

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

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 this:

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

我得到的答案1,因为它不承认为指向数组

I get the answer 1 because its not recognising 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天全站免登陆