Answer to Question #91048 in C++ for Hamad

Question #91048
Can you tell me the logic why you assign pointer pa with names of array and how 1d pointer is working as 2d like storing and accessing values (can you tell me back end programming)
1
Expert's answer
2019-06-24T02:12:05-0400

Pointer is a special type of variable that holds memory address of another variable.

When you declare array like int arr[2] name of that array is actually becomes a pointer that holds address of the first data member of that array. Therefore, if you write:

int arr[2];

int *p;

p = arr;

you will assign value of pointer arr to pointer p and in this way p becomes alternative name for array arr. After such assignment you could use p to access array data members, like:

p[1] = 2;

will assign value 2 to the second element of the array arr, which is equivalent for

arr[1] = 2;

And if you wish to assign pointer not to the first but to second element in the array you could write:

p = &arr[1]; //assigns address of second array data member to the pointer

*p = 2; // assigns value to that member

This will be another equivalent for arr[1] = 2; operation.

When multidimensional (2d, 3d …) array is declared, you should understand that it will be stored in memory as 1d array no matter how many formal dimensions it has. If you declare array x[2][3] it will be stored in memory as a single sequence: x[0][0], x[0][1], x[0][2], x[1][0], x[1][1], x[1][2], x[2][0], x[2][1], x[2][2].

Therefore you could use pointers to access data in 2d array the same way as if it was 1d array.

Let’s say we have 2d array that holds 8 members (4 rows by 2 columns):

int bb[4][2];

int *p;

p = (int*)bb;   //will assign pointer bb value to p (with type conversion)

Now data members of array bb could be accessed using  pointer p as if it points to 1d array:

p[0] is equivalent of bb[0][0]

p[1] is equivalent of bb [0][1]

p[2] is equivalent of bb [1][0]

p[3] is equivalent of bb [1][1]

p[4] is equivalent of bb [2][0]

p[5] is equivalent of bb [2][1]

p[6] is equivalent of bb [3][0]

p[7] is equivalent of bb [3][1] 

Type conversion (int *) is needed because here array name (which is a pointer)  bb points not to the first single integer array member, but to array that consists of single “row” of two integers, therefore bb is a pointer to pointer to first data member of 2 integers sequence. But if you declare p as pointer to pointer, you could access array data members without type conversion during assignment:

int bb[4][2];

int **p;     //pointer to pointer

p = bb;

p[2][1] = 10;   //   equivalent to bb[2][1] = 10;

 


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS