laura
laura

Reputation: 13

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

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

int* a = malloc(...)

Upvotes: 1

Views: 210

Answers (2)

Ted Lyngmo
Ted Lyngmo

Reputation: 117178

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);
}

Upvotes: -1

Carl Norum
Carl Norum

Reputation: 224844

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

Upvotes: 3

Related Questions