How to get the size of dynamically allocated 2d array

前端 未结 4 1793
余生分开走
余生分开走 2021-01-17 06:07

I have dynamically allocated 2D array. Here is the code

int **arrofptr ;
arrofptr = (int **)malloc(sizeof(int *) * 2);
arrofptr[0] = (int *)malloc(sizeof(int         


        
相关标签:
4条回答
  • 2021-01-17 06:14

    You can't find size of arrofptr, because it is only a pointer to pointer. You are defining an array of arrays using that. There's no way to tell the size information with only a pointer, you need to maintain the size information yourself.

    0 讨论(0)
  • 2021-01-17 06:23

    You can't get the length of dynamically allocated arrays in C (2D or otherwise). If you need that information save it to a variable (or at least a way to calculate it) when the memory is initially allocated and pass the pointer to the memory and the size of the memory around together.

    In your test case above sizeof is returning the size of the pointer, and thus your calculation the size of the pointers is usually 4, this is why you got 4 and is likely to have the trivial result of 4, always.

    0 讨论(0)
  • 2021-01-17 06:32

    if you want to keep track of the size of an allocated block of code you would need to store that information in the memory block that you allocate e.g.

    // allocate 1000 ints plus one int to store size
    
    int* p = malloc(1000*sizeof(int) + sizeof(int)); 
    *p = (int)(1000*sizeof(int));
    p += sizeof(int);
    
    ...
    
    void foo(int *p)
    {
      if (p)
      {
        --p;
        printf( "p size is %d bytes", *p );
      }
    }
    

    alt. put in a struct

    struct
    {
      int size;
      int *array;
    } s;
    
    0 讨论(0)
  • 2021-01-17 06:34

    The only return value you get from malloc() is a pointer to the first byte of the allocated region (or NULL on failure). There is no portable, standard, way of getting the associated allocation size from such a pointer, so in general the answer is no.

    The C way is to represent arrays and buffers in general with a pair of values: a base address and a size. The latter is typically of the type size_t, the same as the argument to malloc(), by the way.

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