Number of elements allocated from a pointer

0

I need to know how many elements are allocated in my pointer pointer. For example with vector, sizeof(v)/sizeof(v[0]) in this way I get the number of elements that vector has. I would like to do the same, but with pointers.

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

int main(int argc, char const *argv[]){

    int *p = malloc(5*sizeof(int)), n;
    n = sizeof(p)/sizeof(int);
    printf("%d\n", n);
    return 0;

}

In this code I already know how much elements have, just print the variable n , however I will use this in a function where I do not know the value of n .

    
asked by anonymous 16.04.2017 / 01:40

1 answer

2

There is no standard way of doing this and attempting to use some extension may have interoperability issues.

But also no need to get this information since it is available in the code. In this example the size is 5, so even if it were possible to get it, calculating the size does not make sense. If you need this information at various points put in a variable or constant, which alias is what everyone does even if they do not need the information later, avoiding Magic numbers .

If you need to use this number in another function pass it as the function argument. Obviously the function must be done to receive and use that number. An alternative is to create an abstraction and create a type that has the object and its size as the header. In fact it is like this in higher level languages, there does not need to be anything else.

Look how simple:

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

int main(int argc, char const *argv[]) {
    int n = 5;
    int *p = malloc( n * sizeof(int));
    printf("%d\n", n);
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
16.04.2017 / 01:54