如何计算指针所指向的内存大小? [英] how to calculate size of pointer pointed memory?

查看:248
本文介绍了如何计算指针所指向的内存大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个功能我已经写:

char *ab; 

ab=malloc(10);

然后在另一个功能,我想知道的内存由 AB 指针指向大小。
有什么办法,我可以知道 AB 指向的内存10个字符?

Then in another function I want to know the size of memory pointed by the ab pointer. Is there any way that I can know that ab is pointing to 10 chars of memory?

推荐答案

这是只有免费()肯定知道了深刻的秘密。很可能在你的系统,但在完全实现依赖性。

It's a deep secret that only free() knows for sure. It's likely in your system, but in a totally implementation dependent manner.

有一个有点尴尬,但如果你想保留一切融合在一起:

A bit awkward, but if you want to keep everything together:

typedef struct
{   // size of data followed by data (C only trick! NOT for C++)
    int        dimension;   // number of data elements
    int        data[1];     // variable number of data elements
} malloc_int_t;

malloc_int_t  *ab;

int  dimension = 10;
ab = malloc( sizeof(*ab) + (dimension-1)*sizeof(int) );
ab->dimension = dimension;

ab->data[n]  // data access 

我已经改变了数据类型的 INT 以使code更通用的模板。

I've changed the data type to int to make the code a more generic template.

这篇关于如何计算指针所指向的内存大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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