Getting the size of a malloc only with the returned pointer

后端 未结 5 392
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 11:42

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

相关标签:
5条回答
  • 2020-11-29 12:03

    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.

    0 讨论(0)
  • 2020-11-29 12:15

    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;
    
    0 讨论(0)
  • 2020-11-29 12:16

    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.

    0 讨论(0)
  • 2020-11-29 12:21

    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);
    
    0 讨论(0)
  • 2020-11-29 12:21

    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.

    0 讨论(0)
提交回复
热议问题