可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
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);
回答2:
There's no standard way to do what you ask. Some compilers may provide a function for that, or some other allocators may have such a function, but, as already said there's nothing standard.
Notice that the sizeof
applied over arrays does not work because it recognizes the pointer "as from an array": it just recognizes its argument as an array (sizeof
is one of the few contexts in which an array do not decay to a pointer to its first element); once your array decays to a pointer sizeof
will only yield the size of the pointer.
回答3:
First of all, sizeof() returns the size of a "type"; it doesn't know a thing about allocated memory.
Second, there is no way to get the size of a malloc()ed block, UNLESS you want to dig into the internals of the runtime library of your compiler. Which is most definitely not a good idea, especially since it's no problem to remember the size elsewhere --- you could prefix the memory block with another item to store the size, or you could store it separately.
回答4:
In C standard and portable, it's impossible. Just notice that some compilers provide nonstandard extensions (keep track of it, e.g. msize
).
Besides, the sizeof
operator can't tell you the size of the block, so it yields the size of the pointer (remember that sizeof
operates at compile time, except with variable length arrays).
So you have to keep the size alloced, e.g. in a data structure such as :
#include <stddef.h>
typedef struct {
int *p;
size_t n;
} array;
回答5:
Use a pointer-to-array type rather than a pointer-to-element type:
int (*parray)[10] = malloc(sizeof *parray);
Then sizeof *parray
gives you the desired answer, but you need to access the array using the *
operator, as in (*parray)[i]
(or equivalently albeit confusingly, parray[0][i]
). Note that in modern C, 10
can be replaced with a variable.