Tuesday, July 28, 2009

Pointer of array and array of pointer?

i am unclear about the concept of the following c++ programming even i have read several books.





what are the differences between pointer of array and array of pointer? differences in effects and uses?

Pointer of array and array of pointer?
A pointer is a data spot that holds the location of another data spot. Meaning if P is a pointer its data is some hex code which is a location in memory. That location could be another pointer or actual data. So if Q is actual data (int), P could be a pointer to Q and by referencing P you traverse to the location Q to read the data stored in Q. In P is the location of Q, In Q is the data assigned.





An array of pointers is an array that stores different pointers (each pointing to what-ever it is pointing). A pointer of an array is a Pointer that points to an array (meaning the it has the location of the array).


Arrays are designed so that the elements are stored in location one after the other so by having P++ (adding one to the base value of the pointer that points to the beginning of the array) You change it to hold the location of the next value of the array.
Reply:An array is a stack of data say 1, 2, 3





Array A[0]=1, A[1]=2, A[2]=3





A[0] is a pointer that points to the address that contains the data 1. (A[0] This is a pointer of an array)





An array of pointers is if you have this


Array B[0]=A[0], B[1]=A[2]





Array B[0] is a pointer like A[0] is, but now instead of containing a value 1, it contains a pointer value. (B is an array of pointers)
Reply:So a pointer is the "address of" something.





*char bob is a pointer to a char. in code, *bob would reference that pointer.





So if I have an array of ints:


int i[3];





I can have a pointer to that array of ints:





int iArray[3];


int *p = iArray;





An array of pointers would be just that, an array of memory locations. Each member would either point to unallocated memory until it as set to an allocated location or had space allocated for it.





int *iArrray2[1] //array of one int pointer


int i = 3;





iArray2[0] = %26amp;i;





cout %26lt;%26lt; *iArray2[0] %26lt;%26lt; endl;





will output 3.
Reply:They are very different. A pointer to an array is a single pointer (4 bytes on an x86 system) that holds the address of an array of variables. An array of pointers is a series of pointers that can each hold a memory address.





int arry[5] = { 1, 2, 3, 4, 5 };


int *arryPtr = arry; // Points to the first element of the array


int *arryOfPtrs[5] = { %26amp;arry[0], %26amp;arry[1], %26amp;arry[2], %26amp;arry[3], %26amp;arry[4] };


/* The array of pointers now holds five pointers (5 addresses) each pointing */


/* to one of the elements in the array */

survey research

No comments:

Post a Comment