我如何使用通过malloc分配的指针来知道数组的大小?
How can i know the size of the array using a pointer that is allocated using malloc?
#include <stdio.h> int main(){ int *ptr = (int *)malloc(sizeof(int * 10)); printf("Size:%d",sizeof(ptr)); free(ptr_one); return 0; }在这种情况下,我仅得到指针的大小为8.如何修改代码以获取数组的大小为40.
I get only the size of the pointer in this case which is 8.How to modify the code to get the size of array which will be 40.
推荐答案您不能. 您将需要进行簿记并自己进行跟踪.使用new,您可以分配动态内存,而在分配内存时,您只需调用delete,它就知道它已经分配了多少内存,因为该语言在内部进行处理,因此用户无需费心记账.如果仍然需要它,则需要通过单独的变量进行跟踪.
You cannot. You will need to do the bookkeeping and keep track of it yourself. With new you allocate dynamic memory and while deallocating the memory you just call delete, which knows how much memory it has deallocate because the language takes care of it internally so that users do not need to bother about the bookkeeping. If you still need it explicitly then you need to track it through separate variable.
更多推荐
使用指针知道数组的大小
发布评论