c - 理解C中的解引用运算符和指针,以及一个小程序的逻辑

标签 c arrays string pointers char

我从 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");
    }
} 

我有两个问题:

  1. 为什么我们开始迭代 fori=1 处循环, 为什么不 从 i=0 开始,尤其是当我们结束迭代时 i<argc并且不在 i<=argc ?

  2. 倒数第二、三、四行代码!在 char *pos = argv[i]; ,我们声明一个指针类型变量并赋值给它 指向运行程序时传递的命令行参数的指针。

    然后在while (*pos != '\0') , *pos 取消引用指针 存储在 pos , 所以 *pos包含由指向的实际值 指针存储在 pos 中.

    然后在printf("%c\n", *(pos++)); , 我们有 *(pos++) 和 这才是真正的问题:(a) 他为什么增加 pos , 和 (b) 取消引用的含义是什么 (pos++)与 取消引用运算符 * ?

最佳答案

  1. 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,而是需要更早地停止一个元素,就像处理所有其他数组一样。

  1. 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/

相关文章:

Java : When does corresponding memory come into existence for local variables?

c - CPU寄存器的大小

c - 如何打印数组中元素的数量?

c - 在第一个线程完成之前,第二个线程不会运行

javascript - AngularJS ng-重复数组数组

javascript - ParseFloat 数组值

java - 从带有其他字符的Java字符串中提取时间

php - 性能: Empty string or null in PHP

javascript - 按对象属性值对数组进行数字排序

java - 将整数值转换为字符串时,字符串比较失败,并返回 false boolean 值