简体   繁体   中英

accessing 2d array using pointers in C

In my main I have

  int mat[ROW][COL];
  int *p = &mat[0][0];
  minput(p, ROW, COL);

I'm stuck on how to make minput, because I'm supposed to initialize the 2d array with set numbers, but I just don't understand how I'm supposed to assign the numbers,

I get that m[0][0] in pointer is *(*(m+0)+0) , but it doesn't let me do something like *(*(m+0)+0)=0; ,

because it gives the invalid type argument of unary '*' (have 'int') error.

So basically I just want to know how to assign a number to a 2d array using pointers, if we didn't have to use pointers this would be so easy with m[2][2]=5 and whatever but I have no idea how to do this with pointers.

My prof provided a one line example of the minput function and it was just *(m+0) = 8; , which doesn't make sense to me, isn't that what we use for a 1d array? if that's the way to do it then does that mean I'm supposed to do something like

*(m+0) = 8;
*(m+1) = 1;
*(m+2) = 6;
*(m+3) = 3;
*(m+4) = 5;
*(m+5) = 7;
*(m+6) = 4;
*(m+7) = 9;
*(m+8) = 2;

for a 3x3 array? it doesn't seem right to me, It would be great if someone could help me out with this, pointers are very confusing to me.

EDIT: so I see that apparently the correct way to do it is the way I listed above with the *(*(m+0)+0) = val

but when I do this in my code, I get the this error:

error: invalid type argument of unary ‘*’ (have ‘int’)
  *(*(m+0)+2)=6;
  ^

why is this the case? is the assignment wrong?

Suppose you have 2D array declared as arr[rows][cols] . Then:

  • arr points to the first subarray
  • arr + 1 points to the second subarray
  • *(*(arr+2)+3) is equivalent to arr[2][3]

So if you want to assign a val to the first element of second row for example:

*(*(mat+1) + 0) = val;

That's correct. You can use

*(m + (rowNumber*COL) + colNumber) = val

to access it. Basically the elements in the two-dimensional array are stored consecutively in memory, and m points to the beginning of it. Therefore you can do it in this way as an one-dimensional array. That's why we don't use something like **m, as it's not "a pointer to a pointer", even it's a two-dimensional array.

The way you have it initialized *((p+0) + 0) = 1; would make mat[0][0] = 1;

*((p+0) + 1) = 2; would be mat[0][1] = 2;
*((p+1) + 0) = 3; would be mat[1][0] = 3;

etc..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM