Welcome to OGeek Q&A 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...