Praburaj
Praburaj

Reputation: 613

Knowing the size of the array using pointer

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.

Upvotes: 1

Views: 345

Answers (2)

Gangadhar
Gangadhar

Reputation: 10516

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

Upvotes: 0

Alok Save
Alok Save

Reputation: 206508

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.

Upvotes: 7

Related Questions