CONTOH - CONTOH PROGRAM POINTER C++
Selamat pagi sobat semua. bagi sahabat yang sedang belajar bahasa C/C++ berikut saya share contoh program C yang menggunakan Pointer didalamnya. soal ini dapat sobat gunakan dalam latihan.
1. Contoh deklarasi pointer
#include <iostream>
using namespace std;
int main()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout<<"Firstvalue is "<<firstvalue<<'\n';
cout<<"Secondvalue is "<<secondvalue<<'\n';
return 0;
}
2. Contoh deklarasi pointer
#include <iostream>
using namespace std;
int main()
{
int firstvalue=5, secondvalue=15;
int *p1, *p2;
p1 = &firstvalue; //p1 = address of firstvalue
p2 = &secondvalue; //p2 = address of secondvalue
*p1 = 10; //value pointed to by p1 = 10
*p2 = *p1; //value pointed to by p2 = value pointed to by p1
p1 = p2; //p1=p2 (value of pointer is copied)
*p1=20; // value pointed to by p1 = 20
cout << " Firstvalue is "<<firstvalue<<'\n';
cout<<" Secondvalue is "<<secondvalue<<'\n';
return 0;
}
3. Pointer di dalam array
#include <iostream>
using namespace std;
int main()
{
int numbers [5];
int *p;
p=numbers; *p=10;
p++; *p=20;
p=&numbers[2]; *p=30;
p=numbers + 3; *p=40;
p=numbers; *(p+4)=50;
for (int n=0; n<5; n++)
cout<<numbers[n]<<", ";
return 0;
}
4. Pointer dan fungsi
#include <iostream>
using namespace std;
void increment_all( int *start, int *stop)
{
int * current = start;
while (current != stop) {
++(*current); //increment value pointed;
++current; //increment pointer
}
}
void print_all (const int *start, const int *stop)
{
const int * current = start;
while (current != stop) {
cout << *current << '\n';
++current; //increment pointer
}
}
int main()
{
int numbers[]={10,20,30};
increment_all (numbers, numbers+3);
print_all (numbers, numbers+3);
return 0;
}
5. Pointer dengan fungsi void
#include <iostream>
using namespace std;
void increase (void * data, int psize)
{
if (psize == sizeof(char))
{char * pchar; pchar = (char*)data; ++(*pchar);}
else if (psize == sizeof (int))
{int * pint; pint = (int *)data; ++(*pint);}
}
int main ()
{
char a = 'x';
int b = 1602;
increase (&a, sizeof (a));
increase (&b, sizeof (b));
cout<<a<<", "<<b<<'\n';
return 0;
}