Anda di halaman 1dari 42

Algoritma&Pemrograman2

015

C Pointers
Tim Dosen DTE

PDP2015

Mengapa mempelajari
Pointer?

Pointer sangat berdaya guna (powerful)


Efisien karena dapat menangani jumlah data
yang tidak terbatas (dynamically allocate
memory)
Bandingkan dengan Array yang harus
dialokasikan jumlah memori yang akan dipakai
Inisiasi Array dengan jumlah elemen 100 berarti dari
awal pemrograman telah dipesan sebanyak 100
lokasi memori.
Kenyataannya mungkin dipakai lebih sedikit, atau
butuh lebih banyak

Dapat mengimplementasikan call by reference


Algoritma&Pemrog

Memory address
Setiap variabel yang kita deklarasikan akan
mereservasi suatu lokasi dalam memori
komputer
Lokasi tsb memiliki address
Untuk mengakses address memori tsb, gunakan
tanda & (ampersand)
Contoh:
scanf(%d, &var1);

Artinya kita ingin meminta suatu input integer


dan ingin diletakkan di address memori dimana
var1 telah melakukan reservasi sebelumnya
Algoritma&Pemrog

Code
#include <stdio.h>

Result
Address of var1 variable: 6a33e9ac
Address of var2 variable: 6a33e9a0

int main ()
{
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}

Algoritma&Pemrog

Apa itu Pointer?


Sebuah Pointer sebenarnya juga merupakan
variable
Bedanya dgn variable biasa:
Pointer menyimpan address dari variable lain
Isi pointer adalah address dari variable lain

Variable biasa menyimpan suatu value spesifik direct


reference

Pointer digunakan untuk menunjuk lokasi memori


di mana sebuah value ingin disimpan dengan cara
menyebutkan address dari variable tempat
seharusnya value tsb disimpan indirect
reference
Algoritma&Pemrog

Ayah
Citra

Sedang
kos

Citra

Jalan Baru
no 10
Bayu ingin memberi kado pada Citra
(tapi tidak tau alamatnya). Maka dapat
dilakukan dengan cara:
langsung memberikannya pada Citra
(direct)
menitipkannya ke Ayah Citra (indirect)

Bayu
Algoritma&Pemrog

Ayah Citra berperan sebagai


Pointer atau penunjuk dimana
Citra Berada

Fig. 7.1 | Directly and indirectly referencing a variable.

Algoritma&Pemrog

Pointer Declaration
Tanda* digunakan untuk mendeklarasikan
pointer
<variable_type> *<pointer_var_name>;

Tipe (type) pointer sama dengan tipe variabel


yang ditunjuknya

int *ip; /* pointer to an integer */


double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

Jika ingin mendeklarasikan lebih dari 1 pointer,


tanda * ditulis sebelum tiap nama pointer
variable
int *myPtr1, *myPtr2;

Algoritma&Pemrog

Pointer Initialization
Untuk mendapatkan address dari variable
yang ingin ditunjuk oleh pointer, gunakan
tanda & (address operator)
int y = 5;
int *yPtr;
yPtr = &y;

/* yPtr gets address of y */

yPtr menunjuk ke y
Dengan cara ini berarti kita sudah
melakukan inisialisasi pada pointer
Algoritma&Pemrog

Fig. 7.2 | Graphical representation of a pointer pointing to an integer variable in memory.

Sebuah pointer variable akan lebih baik jika penamaannya


diakhiri Ptr. Hal ini akan memudahkan kita dalam
memprogram
Algoritma&Pemrog

10

Fig. 7.3 | Representation of y and yPtr in memory.

Algoritma&Pemrog

11

#include <stdio.h>
int main ()
{
int

y = 20;

int

*yPtr;

yPtr = &y;

/* actual variable declaration */


/* pointer variable declaration */

/* store address of var in pointer variable*/

printf("Address of y variable: %p\n", &y

);

/* address stored in pointer variable */


printf("Address stored in yPtr variable: %p\n", yPtr );
/* access the value using the pointer */
printf("Value of *yPtr variable: %d\n", *yPtr );
return 0;
}

Algoritma&Pemrog

Address of y variable: 93f0a5a4


Address stored in yPtr variable: 93f0a5a4
Value of *yPtr variable: 20

12

Indirection
Untuk mengakses value secara indirect, gunakan
tanda * (indirection/dereferencing operator)
Contoh sebelumnya:
printf("Value of *yPtr variable: %d\n", *yPtr );

Menghasilkan:
Value of *yPtr variable: 20

Tanda * dapat digunakan untuk mengassign


value secara indirect
*yptr = 7;

dan
lain

&

/* changes y to 7 */

merupakan inverse bagi satu sama

Algoritma&Pemrog

13

Outline
fig07_04.c

(1 of 2 )

If aPtr points to a, then &a and


aPtr have the same value.
a and *aPtr have the same value

&*aPtr and *&aPtr have the same value

Algoritma&Pemrog

14

NULL Pointers
Ada kalanya kita tidak/belum ingin
meng-assign sebuah pointer ke suatu
address variable
Disebut Null Pointer
Meng-assign NULL value ke pointer
Dilakukan saat variable declaration.

Akan sangat berguna ketika


menggunakan linked list
Algoritma&Pemrog

15

#include <stdio.h>
int main ()
{ int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}

The value of ptr is 0

Algoritma&Pemrog

16

Calling Functions by Reference


Mengubah langsung ke lokasi memori
tempat variable disimpan
Menggunakan pointer arguments
Main program, atau pemanggil function
menggunakan operator &
double (&num);

Function menggunakan tanda operator *


void double( int *number )
{
*number = 2 * ( *number );
}

sebagai nickname dari variable


yang dikirimkan (num)

*number

Algoritma&Pemrog

17

Outline
fig07_06.c

Call by Value

Algoritma&Pemrog

18

Outline
Function prototype takes a pointer argument
fig07_07.c

Call by Reference
Function cubeByReference is
passed an address, which can be the
value of a pointer variable

In this program, *nPtr is number, so this


statement modifies the value of number
itself.

Algoritma&Pemrog

19

Fig. 7.9 | Analysis of a typical call-byreference with a pointer argument.

Algoritma&Pemrog
Fig. 7.8 | Analysis of a typical call-by-value.

20

Pointer to Array
Sebenarnya sebuah nama array merupakan
constant pointer pada elemen pertama dari array
tersebut.
Contoh:
double balance[50];

balance secara otomatis adalah pointer ke &balance[0]

Kita dapat juga membuat pointer baru yang


menunjuk ke array
double *pPtr;
double balance[10];
pPtr = balance;

Assign pPtr alamat element pertama dari array balance


tanpa menggunakan tanda &
Algoritma&Pemrog

21

Array values using pointer


*(p + 0) : 1000.0
*(p + 1) : 2.0
#include <stdio.h>
*(p + 2) : 3.4

*(p + 3) : 17.0
int main ()
*(p + 4) : 50.0
{
Array values using balance as address
/* an array with 5 elements */
*(balance + 0) : 1000.0
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
*(balance + 1) : 2.0
double *p;
*(balance + 2) : 3.4
int i;
*(balance + 3) : 17.0
p = balance;
*(balance + 4) : 50.0
/* output each array element's value */
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ )
{
printf("*(p + %d) : %.1f\n",

i, *(p + i) );

}
printf( "Array values using balance as address\n");
for ( i = 0; i < 5; i++ )
{
printf("*(balance + %d) : %.1f\n",

i, *(balance + i) );

}
return 0;

Algoritma&Pemrog
}

22

Passing array to function as


call-by-reference

Karena nama array sudah merupakan


pointer, maka ketika kita mem-passing
array ke function secara by reference,
tidak perlu lagi menggunakan tanda &
Mengirimkan secara by reference pada
contoh sebelumnya:
double (&num); //num adalah variable

Contoh berikutnya:
convertToUppercase( string ); /*string adalah array. Tanpa
tanda & */

Algoritma&Pemrog

23

Outline
fig07_10.c

(1 of 2 )

String is array, so send without &

Algoritma&Pemrog

24

Outline
fig07_10.c

(2 of 2 )
Both sPtr and *sPtr are modified by the
convertToUppercase function

Algoritma&Pemrog

25

Algoritma&Pemrograman2
015

C Structure

PDP2014

26

What is Structure in C?
Array dapat menyimpan beberapa
(banyak) data dengan jenis yang sama
Structure dapat menyimpan beberapa
data dengan tipe yang berbeda-beda.
Namun data yang berbeda-beda
tersebut mempunyai hubungan satu
sama lain.
Structure dapat merepresentasikan
sebuah record
Algoritma&Pemrog

27

Contoh record
Sebuah record dari buku yang disimpan
di perpustakaan akan memiliki atribut
berikut:
Judul
Pengarang
Tema
ID Buku

Algoritma&Pemrog

28

Defining a Structure
Menggunakan struct statement.
struct [Tag_name]
{ type var_member1;
type var_member2;

type var_member n;
};

Struct statement sebenarnya berarti user


ingin mendefiniskan tipe data yang baru,
yang terdiri dari beberapa member variabel
yang tipenya berbeda-beda.
Algoritma&Pemrog

29

Contoh
struct Books
{

char title[50];
char author[50];
char subject[100];
int book_id;

};
Tips: Gunakan huruf besar pada huruf pertama pada
nama Structure Tag_name, untuk membedakannya
dengan variabel biasa
Algoritma&Pemrog

30

Struct record creation


Membuat sebuah record baru dengan
tipe structure yang telah didefinisikan:
struct

<Tag_name>

<record_name>

Contoh:
struct Books Book1; // record Book1 of type Book
struct Books Book2; // record Book1 of type Book

Algoritma&Pemrog

31

Struct record access


Untuk mengakses variable dalam record
yang telah dibuat:
<record_name>.<var_name>;

Contoh:
Book1.book_id = 6495407;

Algoritma&Pemrog

32

#include <stdio.h>

/* book 2 specification */

#include <string.h>

strcpy( Book2.title, Everyday Meal");


strcpy( Book2.author, Yum yum");

struct Books

strcpy( Book2.subject, Cooking");

Book2.book_id = 6495700;
char title[50];
char author[50];

/* print Book1 info */

char subject[100];

printf( "Book 1 title : %s\n", Book1.title);

int book_id;

printf( "Book 1 author : %s\n", Book1.author);

};

printf( "Book 1 subject : %s\n", Book1.subject);


printf( "Book 1 book_id : %d\n", Book1.book_id);

int main( )
{

/* print Book2 info */


struct Books Book1; /* Declare Book2 */

printf( "Book 2 title : %s\n", Book2.title);

struct Books Book2; /* Declare Book2 */

printf( "Book 2 author : %s\n", Book2.author);


printf( "Book 2 subject : %s\n", Book2.subject);

/* book 1 specification */

printf( "Book 2 book_id : %d\n", Book2.book_id);

strcpy( Book1.title, Snow White");


strcpy( Book1.author, Walt Disney");
strcpy( Book1.subject, Kids fiction");
Book1.book_id = 6495407;

Algoritma&Pemrog

return 0;
}

33

Book 1 title : Snow White


Book 1 author : Walt Disney
Book 1 subject : Kids fiction
Book 1 book_id : 6495407
Book 2 title : Everyday Meal
Book 2 author : Yum yum
Book 2 subject : Cooking
Book 2 book_id : 6495700

Algoritma&Pemrog

34

Structures as Function
Arguments

Cara mem-passing structure sama dengan


mempassing variable. Hanya saja pada deklarasi
parameter disebutkan bahwa jenisnya struct
type

functionName

(struct

Tag_name

local_var)

Contoh, jika kita memisahkan bagian print


menjadi sebuah function:
void printBook( struct Books book )
{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}

Algoritma&Pemrog

35

#include <stdio.h>

strcpy( Book1.subject, Kids fiction");

#include <string.h>

Book1.book_id = 6495407;

struct Books

/* book 2 specification */

strcpy( Book2.title, Everyday Meal");


char title[50];

strcpy( Book2.author, Yum yum");

char author[50];

strcpy( Book2.subject, Cooking");

char subject[100];

Book2.book_id = 6495700;

int book_id;
};

printBook( Book1 ); /* print Book1 info */


printBook( Book2 ); /* Print Book2 info */

/* function declaration */
void printBook( struct Books book );

return 0;
}

int main( )
{

void printBook( struct Books book )


struct Books Book1; /* Declare Book2 */

struct Books Book2; /* Declare Book2 */

printf( "Book title : %s\n", book.title);


printf( "Book author : %s\n", book.author);

/* book 1 specification */

printf( "Book subject : %s\n", book.subject);

strcpy( Book1.title, Snow White");


strcpy( Book1.author, Walt Disney");
Algoritma&Pemrog

printf( "Book book_id : %d\n", book.book_id);


}

36

Pointers to Structures
Cara mendeklarasikan pointer ke sebuah
structure sama dengan membuat pointer ke
variabel biasa
struct

<Tag_name>

*<pointer_name>;

Contoh
struct

Books

Algoritma&Pemrog

*book

37

Pointer to Struct Initialization


Untuk mengassign pointer ke record
menggunakan tanda & (sama seperti
mengassign pointer ke variabel)
<pointer_name> = &<record_name>

Contoh
book = &Book1

Untuk mengakses variable dari structure


menggunakan pointer digunakan tanda ->
<pointer_name>-><var_name>

Contoh
book->title
Algoritma&Pemrog

38

#include <stdio.h>

strcpy( Book1.subject, Kids fiction");

#include <string.h>

Book1.book_id = 6495407;

struct Books

/* book 2 specification */

strcpy( Book2.title, Everyday Meal");


char title[50];

strcpy( Book2.author, Yum yum");

char author[50];

strcpy( Book2.subject, Cooking");

char subject[100];

Book2.book_id = 6495700;

int book_id;
};

printBook( &Book1 ); /* pass address of Book1 */


printBook( &Book2 ); /* pass address of Book2 */

/* function declaration */
void printBook( struct Books *book );

return 0;
}

int main( )
{

void printBook( struct Books *book )


struct Books Book1; /* Declare Book1 */

struct Books Book2; /* Declare Book2 */

printf( "Book title : %s\n", book->title);


printf( "Book author : %s\n", book->author);

/* book 1 specification */

printf( "Book subject : %s\n", book->subject);

strcpy( Book1.title, Snow White");


strcpy( Book1.author, Walt Disney");
Algoritma&Pemrog

printf( "Book book_id : %d\n", book->book_id);


}

39

Typedef
Membuat nama baru sebagai tipe data
Sebenarnya hanya membuat alias dari
sebuah tipe data
Digunakan untuk mempersingkat
penulisan
Contoh:
typedef unsigned char byte;
byte b1, b2;

Algoritma&Pemrog

40

Typedef untuk struct


Contoh
typedef struct Books
{

char title[50];
char author[50];
char subject[100];
int book_id;

} Book;

/* Book adalah alias untuk struct Books */

Sehingga ketika membuat record baru cukup


menulis
Book Book1
Book Book2

Algoritma&Pemrog

41

#include <stdio.h>

strcpy( Book1.subject, Kids fiction");

#include <string.h>

Book1.book_id = 6495407;

typedef struct Books

/* book 2 specification */

strcpy( Book2.title, Everyday Meal");


char title[50];

strcpy( Book2.author, Yum yum");

char author[50];

strcpy( Book2.subject, Cooking");

char subject[100];

Book2.book_id = 6495700;

int book_id;
} Book;

printBook( &Book1 ); /* pass address of Book1 */


printBook( &Book2 ); /* pass address of Book2 */

/* function declaration */
void printBook( struct Books *book );

return 0;
}

int main( )
{

void printBook( struct Books *book )


Book Book1; /* Declare Book1 */

Book Book2; /* Declare Book2 */

printf( "Book title : %s\n", book->title);


printf( "Book author : %s\n", book->author);

/* book 1 specification */

printf( "Book subject : %s\n", book->subject);

strcpy( Book1.title, Snow White");


strcpy( Book1.author, Walt Disney");
Algoritma&Pemrog

printf( "Book book_id : %d\n", book->book_id);


}

42

Anda mungkin juga menyukai