Finding length of Dynamic Array in C/C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Maxood
    New Member
    • Dec 2009
    • 1

    Finding length of Dynamic Array in C/C++

    I have the following code:

    int* y = new int[n];

    where n's value will be provided by the user at runtime. I need to know the total memory size that i have allocated to y.

    What function i will use? Wonder if i can use the sizeof operator? Also i i use the sizeof operator in such a situation as:

    int x[10];
    cout<<sizeof(x) ;

    then it returns 40. What is 40 exactly?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You can not work out the size of allocated data from y alone, you need n too

    size = sizeof *y * n;

    That is the size of a single object times the number of objects allocated, if you prefer

    size = sizeof(int) * n;

    int because y is int*.

    The size of x, 40, is the size of the entire array x. This is also the size of a single entry in x, x[4] for example time the number of entries in x. Since x is an array of 10 integers with size 40 you can deduce from this that sizeof int for your system is 40/10 = 4.

    Comment

    • RRick
      Recognized Expert Contributor
      • Feb 2007
      • 463

      #3
      You can not work out the size of allocated data from y alone, you need n too
      ......
      size = sizeof(int) * n;
      That's the problem with using C/C++ arrays. If you want to avoid overflowing or out of bounds elements in the array, you must keep track of the size (i.e. the n value). If this sort of thing seems laborious and dangerous, try the STL vector. It deals with those issues.

      Comment

      • sandipan169
        New Member
        • Aug 2006
        • 2

        #4
        try using _countof()

        Comment

        Working...