Search This Blog

Thursday, January 3, 2013

How to find the size of a dynamically allocated array?

Usually when we pass a pointer to an array to another function, we pass its size also as the parameter.
Which is not required, if the array is dynamically allocated.

We can find the size of a dynamically allocated array using _msize() function.


    TCHAR *szTxt=new TCHAR[256];
    int nArraySize=0;
    nArraySize=    _msize(szTxt)/sizeof(TCHAR);


Example:
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

void GetIntPtrArray(int* ptrInt)
{
    //To find size of Array
    int nSize=_msize(ptrInt)/sizeof(int);
    cout<<"\r\nThe size of the Integer Array is "<<nSize;
}

void GetCharPtrArray(char* ptrchr)
{
    //To find size of Array
    int nSize=_msize(ptrchr)/sizeof(char);
    cout<<"\r\nThe size of the Char Array is "<<nSize;
}
int _tmain(int argc, _TCHAR* argv[])
{
    int *nArr=new int[10];
    GetIntPtrArray(nArr);

    char *szTxt=new char[256];
    GetCharPtrArray(szTxt);

    getch();
    return 0;
}
 
 

No comments:

Post a Comment