Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

c - Getting the size of a malloc only with the returned pointer

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);

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

For example:

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...