2D array and pointer in C - how to access elements?

I have an example with a pointer to a 2D array. Can someone help me understand what is going on in this example?

int main()
{

    int i = 0, j=0, sum0=0, sum1=0;
    int data[4][3] = { {23,55,50},{45,38,55},{70,43,45},{34,46,60}};
    int *Ptr;
    Ptr = *data;    //Why is the indirection operator used here? 
                    // Does Ptr = 23 by this assignment?

    for (i=0; i<4; i++) {
        sum1 = 0;
        for (j = 0; j < 3; j++) {
            sum1 += data[i][j];
        }
        if (sum1 > sum0) {
                 sum0 = sum1;
                 Ptr = *(data + i);     // Seems like this statement makes Ptr
        }                               // point one row below ... what syntax
    }                                   // can you use to access columns then?
                                       // Is it possible to use pointer arithmetic
    for (i=0; i<3; i++)                 // to access elements of data[i][j] that
        printf("%d\n", Ptr[i]);          // are not at j = 0?

  return 0;
}
+5
source share
4 answers

data is a 2 massive array that has 4 rows, and each row has 3 elements (i.e. 4 X 3).

Now Ptr = *data;means that you save the starting address of the 1st line of the pointer variable Ptr. This statement is equivalent Ptr = *(data + 0). Ptr = *(data + 1)- this means that we assign the starting address of the second line.

Then *Ptror *(Ptr + 0)will give you the value of the first element of the line that it points to. Similarly, it *(Ptr + 1)will give you the value of the second element of the string.

for , (3 ). for, Ptr , , sum0 .

int a[5];, , , a[0] 0[a] . , a[0] *(a+0) 0[a] *(0 + a). 2- .

data[i][j] *(*(data + i) + j). i[data][j].

, , " c" yashwant kanetkar.

+13

Ptr = *data; *(data+0)+0, . 0, , , . * (data+0) - , , ( 2D-). , Ptr . - no. , . (*) , . * (*(data+0)+0) **data.

, p , j,

  • (*(p+i)+j) 2D-. - . j - col no.,
  • *(*(p+i)+j) .
  • *(p+i) i-
  • , *(p+i). , (*p)[columns] *p. 2D-.

2d 1D. * Ptr (int *Ptr = *data), no. (Ptr + n) . , .

+4

data - 3- . , " foo", " foo" , *data data, ( ) {23,55,50}.

, : , , Ptr = 23. ( : Ptr - int *, 23 - int.)

, Ptr = *(data+i) Ptr i th data. , data 3- int, 3- int; i, i .

- . data[i][j], j i. , , () Ptr " ", Ptr+1 () 1 Ptr . (, , , , , .)

+1

, , .

:

Ptr = *data;

, :

(Ptr[0] == 23 && Ptr[1] == 55 && Ptr[2] == 50)

Note that Ptr is a pointer, so it contains a memory address, so Ptr is different from 23 (unless the memory address is 23 , which is unlikely to happen).

0
source

All Articles