Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ เข้าถึงสมาชิกอาร์เรย์ด้วย Pointer


Pointer เก็บที่อยู่หน่วยความจำของตัวแปร Dereference pointer คือการดึงค่าที่อยู่ที่นั่น

ตัวอย่าง 1: เข้าถึงสมาชิกเดี่ยว

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {5, 2, 9, 4, 1};
    int *ptr = &arr[2];
    cout << "The value in the second index of the array is: " << *ptr;
    return 0;
}

ผลลัพธ์

The value in the second index of the array is: 9

อธิบาย

ptr เก็บที่อยู่ของ arr[2] (ค่า 9):

int *ptr = &arr[2];

Dereference ด้วย *ptr แสดงค่า 9:

cout<<"The value in the second index of the array is: "<< *ptr;

ตัวอย่าง 2: เข้าถึงทุกสมาชิกด้วย pointer เดียว

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int *ptr = &arr[0];
    cout << "The values in the array are: ";
    for(int i = 0; i < 5; i++) {
        cout << *ptr << " ";
        ptr++;
    }
    return 0;
}

ผลลัพธ์

The values in the array are: 1 2 3 4 5

อธิบาย

ptr ชี้ arr[0] แล้ว for loop dereference *ptr พิมพ์ค่า แล้ว ptr++ ชี้ตัวถัดไป:

int *ptr = &arr[0];
for(int i = 0; i < 5; i++) {
    cout << *ptr << " ";
    ptr++;
}