Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

pointers

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.

like image 946
Vishnu Vivek Avatar asked Apr 13 '13 08:04

Vishnu Vivek


1 Answers

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;
like image 184
Bart Friederichs Avatar answered Oct 23 '22 11:10

Bart Friederichs