Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

Pointers & loops in C

I have a problem with understanding the use of pointers in my C-program. The program is designed to print out all elements in the array. The most confusing part is the for-loop that doesnt seem to make sense for me. What is the value of p from the beginning? How does the loop stop if the condition p < a + n always is true?

    void element(int a[], int n)
   {
     for (int *p = a; p < a + n; p++)
        printf("%d   ", *p);

    }

       int main()
       {
        int f[5] = {1, 2, 3, 4, 5};
        element(f, 5);
        } 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For your code, p points to a[0], then to a[1], then a[2] and so on.

The condition p < a + n is terminating because when you increment p, it makes the pointer p move from a[0] to a[1] and so on, thus increasing its value and a+n is 1+5=6.

So when p reaches 5, condition becomes false in next iteration.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...