'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(...)
Solution 1:[1]
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);
}
Solution 2:[2]
There are zero ways to do that outside of keeping track of it separately from the allocation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Carl Norum |
