Vishnu Vivek Vishnu Vivek - 2 months ago 6
C Question

How to make a pointer point to any array element of a 2D array?

Coming straight to the point,

I want the character pointer

p
to point to the only array element that contains the character '
T
'.

char a[100][100];
char *p;

for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
if(a[i][j] == 'T')
p = a[i][j];


P.S. I tried with various combinations of
*
,
**
, etc but nothing seems to work.

Answer

Use its address:

char a[100][100];
char *p;

for(int i=0;i<4;i++)
  for(int j=0;j<4;j++)
    if(a[i][j] == 'T')
      p = &a[i][j];

a[i][j] is of type char and p is of type char *, which holds an address. To get the address of a variable, prepend it with &.

The * operator on a pointer works the other way round. If you would want to get the 'T' back, you'd use:

 char theT = *p;