C++ 如何使指针指向二维数组的任何数组元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15985628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a pointer point to any array element of a 2D array?
提问by Vishnu Vivek
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.
PS我已经尝试过的各种组合*
,**
等,但似乎没有任何工作。
回答by Bart Friederichs
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 &
.
a[i][j]
is of typechar
和p
is of type 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;
回答by Manolis Ragkousis
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 jtimes away from the begging of that array!
通过写p = a[i]+j;
你实际上说,我们有一个指针指向一个名为a[i]的数组,你指向距离该数组的请求j倍的位置!
回答by Adnan Akbar
change the if part as follows
更改 if 部分如下
if(a[i][j] == 'T' ) {
p = (char *) &a[i][j];
i = 4; break;
}