Home > database >  How to find the number of elements in a pointer array?
How to find the number of elements in a pointer array?

Time:05-16

What are the different ways to find the number of elements in a int array pointer which is allocated with malloc?

int* a = malloc(...)

CodePudding user response:

There are zero ways to do that outside of keeping track of it separately from the allocation.

CodePudding user response:

You can't if you define a to be a plain pointer to the first element in the array. An alternative is to make the size of the array part of the type. So, instead of defining a to be a pointer to an int, you could make it a pointer to an int[size].

It makes it a little cumbersome to work with though since you need to dereference it when you use it.

Example:

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

#define Size(x) (sizeof (x) / sizeof *(x))

int main() {
    
    int(*a)[10] = malloc(sizeof *a);       // the size made part of a's type

    for(unsigned i=0; i < Size(*a);   i) {
        (*a)[i] = i;                       // note: not  a[i]  but  (*a)[i] 
    }

    printf("%zu\n", sizeof *a);  // prints 40 if sizeof(int) is 4
    printf("%zu\n", Size(*a));   // prints 10

    free(a);
}
  •  Tags:  
  • c
  • Related