How can i find the size of a dynamically allocated

2019-07-21 12:06发布

问题:

I've made an array that is dynamically allocated by a cycle. And then a cycle that reads the numbers out of the array but i need to know the size of the array. The array is correct and fully working and has correct values in it. I defined the array like this:

int *array;

Now when i want to use this it wont work because im using a pointer:

int size = sizeof(array)/sizeof(array[0]);

How can i fix it so it works with my pointer?

回答1:

I assume you are allocating the array using one of new or malloc/calloc. In that case, you can't do this. You need to track the size in another variable or use a structure that will track the size for you.