Home > Blockchain >  How to input 2dimensional array using pointers in c
How to input 2dimensional array using pointers in c

Time:09-26

void get(int r,int c,int *ptr){
  int i,j,k;
  
  cout<<"Enter Elements of a matrix:"<<endl;
  for(i=0;i<r;i  ){
    for(j=0;j<r;j  ){
      cin>>k;
      *(ptr   (i*c)   j)=k;
    }
  }
}

This is my code.

*(ptr   (i*c)   j)=k;

Can anyone explain how the above line of code works?

CodePudding user response:

A pointer is an address in memory where some piece of information is stored. This address takes the form of a number. How many bits that number uses is platform-dependent.

Since that address is a number, we can do math with it.

*(ptr   (i*c)   j)=k;

Can be the following when we understand operator precedence and use whitespace.

*(ptr   i * c   j) = k;

We're adding the product of i and c; and then j to the pointer. Then we're dereferencing that whole thing and copying rhe value of k into it.

How this relates to arrays is that the following two lines of code are equivalent:

arr[1] = 456;

*(arr   1) = 456;

If you're dealing with a multi-dimensional array as a single block of memory, you need to multiply the column width by the number of rows down, and then add however many columns over your data is.

Perhaps a visual will help.

Let's consider a 3x3 2-dimensional array. We'll say we've initialized it 1-9.

1  2  3

4  5  6

7  8  9

Now, we can look at this as a 3x3 array, or... we can consider it a single dimensional array with 9 elements.

1  2  3  4  5  6  7  8  9

How can we access 5?

Well, in the first case we would use something like: arr[1][1]. In the second case, we know that 5 is at index 4, so how do we turn [1][1] into [4]?

Given the pattern arr[row][col] we can multiply the row by the length of each row, and then add the col. So arr2d[1][1] turns into arr1d[1 * 3 1]. Lo and behold, 1 3 1 is 4.

Try this with a bigger array:

 1  2  3  4  5
 6  7  8  9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

To get the value 18 we would access: arr2d[3][2] but if this were treated as a single dimensional array: arr1d[3 * 5 2] which is arr1d[17] which gets us... 18.

  • Related