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

Approaching the point

I want the pointer to the character p point to a single element of the array 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]; 

PS I tried with various combinations * , ** , etc., but nothing works.

+7
source share
3 answers

Use his 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 contains the address. To get the address of a variable, add it with & .

The * operator on the pointer works the other way around. If you want to bring 'T' back, you should use:

  char theT = *p; 
+10
source

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 to begging the array with the name a [i] , and you point to the position j in several cases from the begging of this array!

+5
source

change the if part as follows

  if(a[i][j] == 'T' ) { p = (char *) &a[i][j]; i = 4; break; } 
-one
source

All Articles