Tutorial dan Contoh Pointers ke Structure Pemrograman C++

Tutorial dan Contoh Pointers ke Structure Pemrograman C++

Selamat datang kembali di TeknoTips.NET. TeknoTips.NET adalah media online Indonesia yang diluncurkan pada bulan Maret 2015. Kami berkomitmen menyajikan konten seputar teknologi yang berkualitas dan bermanfaat. Ulasan kami terdiri dari berbagai topik: pemrograman komputer & database, review produk, tutorial windows, linux, android, kumpulan source code & project program, referensi tugas akhir & skripsi, download ebook, game & software.

Pada kesempatan ini kita akan mengulas artikel yang berjudul : Tutorial dan Contoh Pointers ke Structure Pemrograman C++.

A pointer variable can be created not only for native types like (int, float, double etc.) but they can also be created for user defined types like structure.
C++ Structure, Structure and Function, C++ Pointers to Structure, C++ Enumeration
For example:
#include <iostream>
using namespace std;
struct temp {
    int i;
    float f;
};
int main() {
    temp *ptr;
    return 0;
}
This program creates a pointer ptr of type structure temp.

Example 1: Pointers to Structure

#include <iostream>
using namespace std;
struct Distance {
    int feet;
    float inch;
};
int main() {
    Distance *ptr, d;

    ptr = &d;
    
    cout << "Enter feet: ";
    cin >> (*ptr).feet;
    cout << "Enter inch: ";
    cin >> (*ptr).inch;
 
    cout << "Displaying information." << endl;
    cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";

    return 0;
}

Output
Enter feet: 4
Enter inch: 3.5
Displaying information.
Distance = 4 feet 3.5 inches
In this program, a pointer variable ptr and normal variable d of type structure Distance is defined. The address of variable d is stored to pointer variable, that is, ptr is pointing to variable d. Then the member function of variable d is accessed using pointer.

Note: Since pointer ptr is pointing to variable d in this program, (*ptr).inch and d.inch is exact same cell. Similarly, (*ptr).feet and d.feet is exact same cell.
The syntax to access member function using pointer is ugly and there is alternative notation -> which is more common.
ptr->feet is same as (*ptr).feet
ptr->inch is same as (*ptr).inch
Untuk mendapat notifikasi setiap artikel terbaru, masukkan e-mail anda disini
Selanjutnya cek e-mail anda untuk verifikasi.

Silahkan tuliskan komentar relevan Anda dengan jelas dan sopan, sesuai dengan topik postingan tentang ", " pada halaman dibawah ini.

0 Response to "Tutorial dan Contoh Pointers ke Structure Pemrograman C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2


Iklan Bawah Artikel