How to get the size of dynamically allocated 2d array

前端 未结 4 1827
余生分开走
余生分开走 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条回答
  •  旧时难觅i
    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;
    

提交回复
热议问题