当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - 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.

网友答案:

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;
网友答案:

there is another way to get it

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;

By writing p = a[i]+j; you actually say, We have a pointer at the begging of an array called a[i] and you point to the position that is j times away from the begging of that array!

网友答案:

change the if part as follows

  if(a[i][j] == 'T' ) {
       p = (char *) &a[i][j];
       i = 4; break;
  }
分享给朋友:
您可能感兴趣的文章:
随机阅读: