Monday, July 27, 2009

C++, dynamic arrays and returning pointers?

I understand how to do parts of this problem but not sure how to put them together.





Write a function that dynamically allocates an array of integers. The function should accept an integer argument indicating the number of elements to allocate. The function should return a pointer to the array.





Could someone please show me how it is done?

C++, dynamic arrays and returning pointers?
Below is a sample function that allocates space for an array of integer and assigns values to the array





int* doit(int num)


{


int* addr = new int[num];


for(int i = 0; i%26lt; num; i++)


addr[i] = i;


return addr;


}





The return type for this function is a int* (a pointer to an integer) . A memory address that states where the array was created.





the line: int* addr = new int[num];


creates a new array of integers of length num, and the location of that array is stored in the variable addr.





You can then return this value to the caller as we have done in the last line as follows:


return addr;





We can then use the pointer in other code as follows;


int* bleck = doit(5);


bleck[5] = 17;


No comments:

Post a Comment