Knowing the size of the array using pointer

孤者浪人 提交于 2019-12-18 09:45:01

问题


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;
}

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.


回答1:


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.




回答2:


if your machine is 32 bit you will get pointer size always 4 bytes of any data type

if your machine is 64 bit you will get pointer size always 8 bytes of any data type

if you declare static array you will get size by using sizeof

int a[10];

printf("Size:%lu",sizeof(a));

But you did not get the size of array which is blocked by pointer. where the memory to the block is allocated dynamically using malloc .

see this below code:

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

int main()
{
  int i;
  int *ptr = (int *)malloc(sizeof(int) * 10);
  //  printf("Size:%lu",sizeof(ptr)); 
  // In the above case sizeof operater returns size of pointer only.   
    for(i=1;ptr && i<13 ;i++,ptr++)
       {
    printf("Size:%d  %p\n",((int)sizeof(i))*i,ptr);

       }

    return 0;
}

output:

Size:4  0x8ec010
Size:8  0x8ec014
Size:12  0x8ec018
Size:16  0x8ec01c
Size:20  0x8ec020
Size:24  0x8ec024
Size:28  0x8ec028
Size:32  0x8ec02c
Size:36  0x8ec030
Size:40  0x8ec034  //after this there is no indication that block ends. 
Size:44  0x8ec038
Size:48  0x8ec03c


来源:https://stackoverflow.com/questions/18570362/knowing-the-size-of-the-array-using-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!