Connecting Tech Pros Worldwide Forums | Help | Site Map

getting the size of dynamic array

Newbie
 
Join Date: Feb 2008
Posts: 7
#1: Feb 13 '08
Hello there
i wanna get the the size of a dynamic array of integer type which i have created like that.........

Expand|Select|Wrap|Line Numbers
  1.            int *arr=0;
  2.            arr = createTempArray();
  3.            arr =  storeRowValues(arr);
  4.            arr =  storeColValues(arr);
  5.            check(arr);
  6.          }
  7.         }
  8.      }
  9.     int* createTempArray()
  10.       {
  11.         int length = rowIndex+colIndex;
  12.         int *tempArray = new int[length];
  13.          return tempArray;
  14.       }
  15.       int *storeRowValues(int *tempArr)
  16.       {
  17.         for(int i=0;i < colIndex; ++i)
  18.         {
  19.            tempArr[i]=array[rowIndex][i];
  20.         }
  21.         return tempArr;
  22.       }
  23.       int *storeColValues(int *tempArr)
  24.       {
  25.       int size = sizeof(tempArr) / sizeof(tempArr[0]);
  26.  
  27.         for(int i=0; i < size; i++)
  28.          { if(tempArr[i]==7)
  29.            {
  30.         --i;
  31.         break;
  32.            }
  33.          }

I wanna get the the value of size in

storeColValues(int *tempArr) method ..............

**********code***********
Expand|Select|Wrap|Line Numbers
  1. int size = sizeof(tempArr) / sizeof(tempArr[0]);
this line always gives me a result of 1



somebody please help me and give me some hint or piece of code so that i can find the size correctly........

Ganon11's Avatar
Moderator
 
Join Date: Oct 2006
Location: New York, United States of America
Posts: 3,428
#2: Feb 13 '08

re: getting the size of dynamic array


When you pass an array (or pointer to an array) to a function, the function doesn't know for certain if it is an array or not - it just gets an address. It assumes this address is pointing to 1 - and only 1 - element. Thus, the sizeof(array) call returns the size of that pointer, not the size of the entire array.

The only way for a function to know the size of an array is to pass the length as an argument, or use the length as a global constant variable.
Expert
 
Join Date: Sep 2007
Location: VA
Posts: 419
#3: Feb 14 '08

re: getting the size of dynamic array


In visual c++ you can use the _msize() to get the size of the dynamic array. This is not a standard c++ function so it is not portable. Other than that you are stuck with having to create a variable for the array size.
Reply