cp.engr
cp.engr

Reputation: 2489

Point to an array within a 2D array in C

EDIT2: I tried to approximate my actual code here, but apparently I missed something, since this code isn't generating the warnings I'm getting in my actual code. I'm closing this until I can figure out the discrepancy.

Original Question

What is the syntax for pointing to an array (row) within a 2D array such as shown below? How then would I access individual elements within it using the row pointer?

int arr[3][4] =
{
    {0, 1, 2, 3},
    {4, 5, 6, 7},
    {8, 9, 10, 11},
};

EDIT:

If I do

int const * pRow = arr[1];

I get the compiler warning

warning C4047: '=': 'const int *' differs in levels of indirection from 'const int (*)[4]'

Is there a "right" way to do this, besides just forcing it with casts?

Upvotes: 0

Views: 75

Answers (2)

Mohit Yadav
Mohit Yadav

Reputation: 471

You can use this int * ptr_to_row=arr[row_no];

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409196

arr[m] is an array of int, and as all arrays it naturally decays to a pointer to its first element. Now what is the type of the first element of arr[m] (i.e. arr[m][0])? It's an int right? So arr[m] decays to a pointer to int, i.e. int*.

That means you can do something like

int *ptr_to_arr_1 = arr[1];

You can use ptr_to_arr_1 as any other array or pointer. So to access the second element you have ptr_to_arr_1[1], and it's the same as arr[1][1].

Upvotes: 2

Related Questions