Function that returns the size of the memory location occupied by variable c++

I am studying for an exam I have next week and am having troubles understanding Dynamic memory allocation. I have a question given which I dont know how to answer;

line 4: int *arr = new int[3];

Write a function that includes the line 4 above and returns the size of the memory location occupied by variable arr. Use the signature:

int size_of_variable_star_arr() ;

I assume I should be using both a main.cpp and a function.cpp - the main file should contain the array variables, while the function file should contain the array that returns it.

Not entire sure what to do here though in order to return the size of the memory location.

 //Main.cpp
 #include <iostream>
using namespace std;

int main(){
//int *arr = new int[3];

arr[0] = 1;
arr[1] = 2; 
arr[2] = 3;
arr[3] = 4;

cout << "Array: ";
}


 //function.cpp
 #include <iostream>
 using namespace std;

 int size_of_variable_star_arr(){
 int *arr = new int[3];
   for(int i = 0; i < 4; i++){
       cout << arr[i] << " ";
  }
  return 0;
}

1 answer

  • answered 2018-07-11 05:53 geza

    This is a really strange question, but here's the answer anyway:

    int size_of_variable_star_arr() {
        int *arr = new int[3];
        delete [] arr;
        return sizeof(arr);
    }
    

    Notes:

    • I added delete [] to undo the (unnecessary) new
    • It returns the size of variable arr, as stated in the question. Not the size of the memory block which arr points to.