理解 C 中的解引用、取址和数组下标运算符 [英] Understanding the dereference, address-of, and array subscript operators in C
问题描述
我将 argv[] 定义为 char *.使用以下 printf 语句:
I have argv[] defined as a char *. Using the following printf statements:
printf("%s\n",argv[1]); // prints out the entire string
printf("%p\n",&argv[1]); // & -> gets the address
printf("%c\n",argv[1][0]);// prints out the first char of second var
printf("%c\n",*argv[1]); //
这是最后一个我不明白.打印 *argv[1]
是什么意思?为什么和 *argv[1][0]
不一样,为什么不能打印出 printf("%s\n",*argv[1]);代码>.另外,为什么
&*argv[1]
和 &argv[1]
是不同的地址?
It's this last one I don't understand. What does it mean to print *argv[1]
? why isn't that the same as *argv[1][0]
and how come you can't print out printf("%s\n",*argv[1]);
. Also, why is &*argv[1]
a different address then &argv[1]
?
推荐答案
数组下标操作 a[i]
定义为 *(a + i)
- given地址 a
,从该地址偏移 i
元素(不是字节)并取消引用结果.因此,给定一个指针p
,*p
等价于*(p + 0)
,等价于p[0]
.
The array subscript operation a[i]
is defined as *(a + i)
- given the address a
, offset i
elements (not bytes) from that address and dereference the result. Thus, given a pointer p
, *p
is equivalent to *(p + 0)
, which is equivalent to p[0]
.
argv
的类型为 char **
;鉴于此,以下所有情况都是正确的:
The type of argv
is char **
; given that, all of the following are true:
Expression Type Value
---------- ---- -----
argv char ** Pointer to a sequence of strings
*argv char * Equivalent to argv[0]
**argv char Equivalent to argv[0][0]
argv[i] char * Pointer to a single string
*argv[i] char Same as argv[i][0]
argv[i][j] char j'th character of i'th string
&argv[i] char ** Address of the pointer to the i'th string
由于argv[i][j]
的类型是char
,*argv[i][j]
是无效的表达.
Since the type of argv[i][j]
is char
, *argv[i][j]
is not a valid expression.
这是 argv
序列的一个糟糕的可视化:
Here's a bad visualization of the argv
sequence:
+---+ +---+ +---+
argv | | ---> argv[0] | | ---------------------------> argv[0][0] | |
+---+ +---+ +---+ +---+
argv[1] | | -------> argv[1][0] | | argv[0][1] | |
+---+ +---+ +---+
... argv[1][1] | | ...
+---+ +---+ +---+
argv[argc] | | ---||| ... argv[0][n-1] | |
+---+ +---+ +---+
argv[1][m-1] | |
+---+
这可能有助于解释不同表达式的结果.
This may help explain the results of different expressions.
这篇关于理解 C 中的解引用、取址和数组下标运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!