Monday, July 27, 2009

Help with pointers & arrays in C+?

This is my prompt:





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.





This is my code:


int* alloFUN(int num)


{


int* ptrArray = new int[num];


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


{


ptrArray[x] = x;


}


return ptrArray;


}





My only question is about the last part, "The function should return a pointer to the array." Am I doing that right? It doesn't say return the pointer...?

Help with pointers %26amp; arrays in C+?
By definition, the value of a variable—or expression—of type array is the address of element zero. The name of an array is a synonym for the location of the initial element.





Using the unary operator '%26amp;' (addressOf operator):





ptrArray is the same as %26amp;ptrArray[0].





For instance, when an array name is passed to a function, what is passed is the location of the initial element. The function can then use offsets to process the rest of the array.





Note that there is one difference between an array name and a pointer. A pointer is a variable; whereas, an array name is not.


No comments:

Post a Comment