< 所有主题
打印

4.2.指针遍历数组

练习2:指针遍历数组

演示视频:https://www.bilibili.com/video/BV1xqfxBFE4B

利用指针遍历整型数组,体会指针算术运算。

int main() {

    int arr[5] = {1, 2, 3, 4, 5};

    for (int i = 0; i < 5; ++i) {

        std::cout << arr[i] << ” “;

    }

    std::cout << “\nUsing range-based for loop: “;  

    for(auto element : arr) {

        std::cout << element << ” “;

    }   

    int *p = arr; // p points to the first element of the array

    std::cout << “\nUsing pointer to access array elements: “;

    for (int i = 0; i < 5; ++i) {

        std::cout << *p << ” “; // Accessing array elements using pointer arithmetic

        p++; // Move the pointer to the next element

    }

    return 0;

}

目录