Get size of a two-dimensional array

-2

I have a two-dimensional array of char dynamically allocated, how do I get its size?

I would use sizeof (client);

For example, I instantiated a struct client, Customer ** customer; then in the code I'm allocating it as it goes (tamVetor ++ and realloc); receiving data in its structure:

int tamVetor = 0; example: client = realloc (sizeof (char *) tamVetor);                   client [i] = malloc (sizeof (char ) * 150);

In the function that this code is implemented, I can print the x indices of the struct through a for where (int i = 0; i

asked by anonymous 01.07.2018 / 02:57

1 answer

1

It is not possible to determine how much memory was allocated from just the pointer.

sizeof(p) is not able to determine at run time the size of the memory block that was previously allocated. sizeof(p) returns the size of the pointer variable p , which in turn is calculated at compile time.

p stores only the starting address of the memory block that has been allocated.

Whenever you allocate a block of memory, malloc() returns the starting address of that block, but the end of the block can not be determined from it, since there is no terminator type to delimit the end of that block.

You are the one who should know where the end of the block is, so you should store the length of the block somewhere to remember its exact size. p>

On the other hand, you can implement a mechanism capable of retaining the size of the allocated block together with its pointer, for example:

#include <stdlib.h>
#include <stdio.h>

struct pointer_s
{
    size_t size;
    void * p;
};

typedef struct pointer_s pointer_t;

pointer_t * my_malloc( size_t s )
{
    pointer_t * ptr = malloc(sizeof(pointer_t));
    ptr->p = malloc(s);
    ptr->size = s;
    return ptr;
}

void my_free( pointer_t * ptr )
{
    free(ptr->p);
    free(ptr);
}

int main( void )
{
    pointer_t * p = my_malloc( 123 );

    printf( "%ld\n", p->size );

    my_free( p );

    return 0;
}
    
01.07.2018 / 04:10