Coming straight to the point,
直截了当地说,
I want the character pointer p
to point to the only array element that contains the character 'T
'.
我希望字符指针p指向唯一包含字符'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.
附注:我尝试了各种组合的*,**等,但似乎没有任何效果。
3 个解决方案
#1
10
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 &
.
[i][j]是char类型的,p类型是char *,它持有一个地址。要获取变量的地址,请在其前面加上&。
The *
operator on a pointer works the other way round. If you would want to get the 'T'
back, you'd use:
指针上的*操作符反过来工作。如果你想把T拿回来,你可以用:
char theT = *p;
#2
5
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!
写p = a[i]+j;你会说,我们有一个指针指向一个叫a[i]的数组,你指向那个位置,这个位置是j的距离,而不是那个数组的请求!
#3
-1
change the if part as follows
更改if部分如下所示
if(a[i][j] == 'T' ) {
p = (char *) &a[i][j];
i = 4; break;
}
#1
10
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 &
.
[i][j]是char类型的,p类型是char *,它持有一个地址。要获取变量的地址,请在其前面加上&。
The *
operator on a pointer works the other way round. If you would want to get the 'T'
back, you'd use:
指针上的*操作符反过来工作。如果你想把T拿回来,你可以用:
char theT = *p;
#2
5
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!
写p = a[i]+j;你会说,我们有一个指针指向一个叫a[i]的数组,你指向那个位置,这个位置是j的距离,而不是那个数组的请求!
#3
-1
change the if part as follows
更改if部分如下所示
if(a[i][j] == 'T' ) {
p = (char *) &a[i][j];
i = 4; break;
}