本文介绍了当使用指向数组的指针时,我们要迭代什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是查找特定字母出现的简单功能.

This is a simple function for finding occurrences of a specific letter.

1:  int count_x(char *p, char a)
2:  {
3:      int count = 0;
4:      while(*p != '\0')
5:      {
6:        if (*p == a)
7:            count++;
8:        p++;
9:      }
10:      return count;
11:  }

我们可以使用p[n]来访问特定元素,或者我们可以取消引用*p并获取该数组的第一个元素作为示例,而我们通常会做所有这些事情.
对我来说奇怪的是位于第8行.当我们写p++时,我们从一开始就获得了传递-1符号的数组.因此,如果它是hello, world,那么它将是ello, world.我们正在某种程度上遍历索引,但是我真的不明白如何做.

We can get access to a specific element by using p[n], or we can dereference it *p and get a first element of that array as an example, and all of that stuff we usually do.
The strange thing to me is located at the line number 8.When we write p++, we are getting the array we passed -1 symbol from the beginning. So if it was hello, world then it would be ello, world.We are somehow iterating throuhg the indices but i don't really understand how.

我可以解释所有这些东西如何工作吗?

Can i have an explanation of how all of that stuff works?

推荐答案

循环条件*p != '\0'表示:*迭代直到p指向的值是'\0'.循环体内的语句

The loop condition *p != '\0' means: *iterate until the value pointed by p is '\0'. The statement inside the loop body

p++;

递增指向所传递字符串的下一个字符的指针.

increments the pointer to next character of the string passed.

第一次迭代

+--------+--------+--------+--------+--------+--------+--------+--- ----+--------+--------+--------+--------+
|        |        |        |        |        |        |        |        |        |        |        |        |
|  'h'   |  'e'   |  'l'   |  'l'   |  'o'   |  ','   |  'w'   |  'o'   |  'r'   |  'l'   |  'd'   |  '\0'  |
|        |        |        |        |        |        |        |        |        |        |        |        |
+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
  ^
  |
  p

第二次迭代:

+--------+--------+--------+--------+--------+--------+--------+--- ----+--------+--------+--------+--------+
|        |        |        |        |        |        |        |        |        |        |        |        |
|  'h'   |  'e'   |  'l'   |  'l'   |  'o'   |  ','   |  'w'   |  'o'   |  'r'   |  'l'   |  'd'   |  '\0'  |
|        |        |        |        |        |        |        |        |        |        |        |        |
+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
             ^
             |
             p

,依此类推.当p到达点'\0'时,条件*p != '\0'变为false,循环终止.在每次迭代中,指针p都会更改其指向的位置.字符串保留在其初始存储位置.

and so on. When p comes to point '\0', condition *p != '\0' becomes false and loop terminates.On every iteration it is the pointer p which changes the location where it points. String remain at its initial stored location.

这篇关于当使用指向数组的指针时,我们要迭代什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:39