Size of a dynamic array

Asked

Viewed 329 times

0

I’m testing with dynamic memory allocation, but when I try to get the array size I always get the same result.

int main()
{
    int *teste=malloc(sizeof(int) * 10);
    int len=sizeof(teste) / sizeof(int);

    print("%i\n", len);
    return 0;
}

Compiling with gcc:

bash-4.2$ ./teste
2

It doesn’t matter if I put sizeof(int) * 100 or 10, always returns 2 :( What am I doing wrong?

  • 1

    I believe it’s because you’re calculating the size of a pointer, not a array. Why pointers have fixed size independent of the pointed type?

  • I think that may be the case, but then another question arises.. how to get the size of a dynamic array, need to do a structure or other location to save the size?

2 answers

1

The idiomatic sizeof(teste) / sizeof(int) is only able to calculate the size in bytes of statically allocated buffers:

int teste[ 123 ];
printf("%d\n", sizeof(teste) / sizeof(int) ); /* 492 / 4 = 123 */

In your case, teste is a pointer to a dynamically allocated memory region and sizeof(teste) is the size in bytes that this pointer occupies, not the size of the memory it is pointing to.

int * teste = NULL;
printf("%d\n", sizeof(teste) / sizeof(int) ); /* 8 / 4 = 2 */

How about:

int main()
{
    int len = sizeof(int) * 10;
    int *teste=malloc(len);

    print("%d\n", len); /* 40 */

    free(teste);
    return 0;
}

0

Thank you for your contributions, in your example Lacobus in my project would not work because I do not know the size of the array when creating and I always relocate (realloc) but I remembered something that can be done, beyond the data structure classes.

I made a structure

struct __buf {
   int *ptr;
   int len;
};

As I adjust the size of the array I update the structure, so:

__buf buffer_serial;
...
buffer_serial.ptr = malloc ( sizeof(int) * len);
buffer_seria.len = len;
...
  • 1

    I’m glad it worked out, fdavid , but that’s basically the application of colleague @Lacobus' answer, which is to save the size in a variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.