我从 here 得到了这个代码片段:
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i) {
char *pos = argv[i];
while (*pos != '\0') {
printf("%c\n", *(pos++));
}
printf("\n");
}
}
我有两个问题:
为什么我们开始迭代
for
在i=1
处循环, 为什么不 从i=0
开始,尤其是当我们结束迭代时i<argc
并且不在i<=argc
?倒数第二、三、四行代码!在
char *pos = argv[i];
,我们声明一个指针类型变量并赋值给它 指向运行程序时传递的命令行参数的指针。然后在
while (*pos != '\0')
,*pos
取消引用指针 存储在pos
, 所以*pos
包含由指向的实际值 指针存储在pos
中.然后在
printf("%c\n", *(pos++));
, 我们有*(pos++)
和 这才是真正的问题:(a) 他为什么增加pos
, 和 (b) 取消引用的含义是什么(pos++)
与 取消引用运算符*
?
最佳答案
- Why are we starting the iterations of for loop at i=1, why not start it at i=0, especially when we are ending the iterations at i
我们从 1 开始,因为 argv[0]
包含我们不关心的程序本身的名称。忽略数组的第一个元素不会移动最后一个数组的索引。
我们将 argc
元素存储在 argv[]
中。因此,我们不能运行到 i==argc
,而是需要更早地停止一个元素,就像处理所有其他数组一样。
- The second, third and fourth last lines of code! In char *pos = argv[i];, we declare a pointer type variable and assign it a pointer to a commandline parameter passed when running the program.
正确。 pos
是一个指针,指向通过命令行传递的第一个字符串。
Then in while (*pos != '\0'), *pos dereferences the pointer stored in pos, so *pos contains the actual value pointed by the pointer stored in pos.
*pos
包含我们当前正在检查的字符串的第一个字符。
Then in printf("%c\n", *(pos++));, we have *(pos++), and that is the actual question: (a) Why did he increment pos, and (b) what is the meaning of dereferencing (pos++) with the dereference operator *?
这里有两件事:
1. (pos++)
:pos
是一个指向char
的指针,用++
递增指针指向下一个元素,即在获取其值后到下一个 char
。
2. pos
的值(在后递增之前)被获取并取消引用以读取该位置的 char
。
因此 while
循环将读取所有字符,而 for
循环处理所有字符串。
关于c - 理解C中的解引用运算符和指针,以及一个小程序的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43469485/