This is more of a theory question than a specific question to a problem.
Let's say I have dynamically allocated an array on the heap:
Now, without knowing the value of numitems, one can figure out the number of declared elements in an array with:Code:int numitems; double *ptr; scanf("%d",&numitems); ptr = (double*) calloc(numitems,sizeof(double));
(or they can divide by sizeof(array_type) )Code:num_elements = sizeof(array_name)/sizeof(array_name[0])
However, when working with pointers, I have not been able to find a method to do the same thing.
returns 4, the size of the memory address andCode:sizeof(*ptr);
returns 8, the size of a doubleCode:sizeof(ptr);
How can one find the number of elements in a dynamically allocated array with the use of pointers?
The reason I'm asking this is because I had been working on a semester project for my programming class in college. Coming from my c++ beginnings, this was a very frustrating problem, since in c++ you can just use .length() to figure this out. In my project, I had multiple functions being called in other functions. While the original function did not need to know the number of elements in the array, the various functions being called did. Therefore, I initially set out to solve this problem using a sizeof() technique rather than adding a parameter to functions that did not need to know the number of elements. After no luck, I finally just added the extra parameter to the functions.
While I know just adding the extra parameter is most likely the easiest method, I am still curious as to how one can find the size of the whole array a pointer is pointingto, rather than a single element, without access to the array itself. It has to be able to be done, since the size of the array must be stored somewhere in order forto work correctlyCode:free(ptr)
I'm sorry for the long post, and I extremely appreciate any help or hints.
Austin