Number of elements allocated from a pointer

Asked

Viewed 127 times

0

I need to know how many elements are allocated in my pointer pointer. For example with vector, sizeof(v)/sizeof(v[0]) this way I get the number of elements that this vector has. I would like to do the same thing, 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 many elements have, just print the variable n, but I will use this in a function where I don’t know the value of n.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

2

There is no standard way to do this and trying to use some extension may have interoperability problems.

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

If you need to use this number in another function, pass it as the argument of the function. Obviously the function must be done to receive and use this number. An alternative is to create an abstraction and create a type that has the object and its size as a header. In fact, it’s like this in higher-level languages, so you don’t have to pass 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("%p = %d\n", (void *)p, n);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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