Caleb Caleb - 3 months ago 18
C Question

What do we iterate through when using pointer to an array?

This is a simple function for finding an 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: }


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?

Answer

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.

For first iteration

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

Second iteration :

+--------+--------+--------+--------+--------+--------+--------+--- ----+--------+--------+--------+--------+
|        |        |        |        |        |        |        |        |        |        |        |        |
|  'h'   |  'e'   |  'l'   |  'l'   |  'o'   |  ','   |  'w'   |  'o'   |  'r'   |  'l'   |  'd'   |  '\0'  |
|        |        |        |        |        |        |        |        |        |        |        |        |
+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
             ^
             | 
             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.

Comments