0

I'm currently working on Exercise 3.35 in C++ Primer Fifth edition ! I've done this exercise using a while loop . But when I come to try this exercise using a for loop , I couldn't solve problem of changing an array element value . (I did solve the problem but not using pointers).
What I need is that if you can help me solve this exercise to change value of array using pointers in a for loop.

Exercise it self
Using pointers, write a program to set the elements in an array to 0(zero);

My code with using pointers

int main()
{    
    int arr[] = {1,2,4,6,8,10,12,14,16,18};
    int *pbeg = begin(arr);
    int *pend = end(arr);

    while (pbeg != pend)
    {
        pbeg[0]=0;
        ++pbeg;
    }   
    for (auto ii : arr)
    {
        cout<<ii<<" ";
    }
    keep_window_open("~");
    return 0;
}  

for loop code I've done

int main()
{    
    const size_t ar =10;
    int arr[ar] = {1,2,4,6,8,10,12,14,16,18};

    for (size_t i = 0; i < ar; ++i)
    {
        arr[i]=0;
    }
    for (auto ii : arr)
    {
        cout<<ii<<" ";
    }
    keep_window_open("~");
    return 0;
}  

In this for loop I haven't used any pointers.

4

1 回答 1

2

尝试这个:

for(int i = 0; i < size; i++) {
    *(pbeg+i) = 0;
}

pbeg 是您的内存地址,因此您添加 i 以向前移动这么多元素。

于 2013-07-05T23:51:33.490 回答