Z00810020120164096COMP6047 (T) Pert 13&14 - Pointer and Arrays

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

Subject : COMP6047

ALGORITHM AND PROGRAMMING


Year : 2015

Pointers and Arrays (T)


Learning Outcomes
At the end of this session, student will be able to:
• Explain the concept of array data and pointer
(LO2 & LO3)

COMP6047 - Algorithm and Programming 2


Sub Topics
Pointers and Arrays:
– Pointer Definition
– Pointer Concept
– Pointer to Pointer
– Array Definition
– Array Initialization
– Pointer Constant & Pointer Variable
– Accessing Array
– 2 and 3 Dimensional Array
– String Manipulation
– Program Examples
– Exercise
– Review

COMP6047 - Algorithm and Programming 3


Pointer Definition
• Pointer is a variable that store the address of another variable
• Syntax :
<type> *ptr_name;
• Two operators mostly used in pointer : * (content of) and &
(address of)
• Example:
Initialize an integer pointer into a data variable:
int i, *ptr;
ptr = &i;
To assign a new value to the variable pointed by the pointer:
*ptr = 5; /* means i=5 */

COMP6047 - Algorithm and Programming 4


Pointer Concept

COMP6047 - Algorithm and Programming 5


Pointer to Pointer
• Pointer to pointer is a variable that saves another address of a
pointer
• Syntax:
<type> **ptr_ptr ;
• Example:
int i, *ptr, **ptr_ptr;
ptr = &i;
ptr_ptr = &ptr;
To assign new value to i:
*ptr = 5; // means i=5 ;
**ptr_ptr = 9; // means i=9; or *ptr=9;

COMP6047 - Algorithm and Programming 6


Pointer to Pointer

COMP6047 - Algorithm and Programming 7


Array Definition
• Data saved in a certain structure to be accessed as a group or
individually. Some variables saved using the same name
distinguish by their index.

• Array characteristics:
– Homogenous
All elements have similar data type
– Random Access
Each element can be reached individually, does not
have to be sequential

COMP6047 - Algorithm and Programming 8


Array Definition
(One Dimensional Array)

• Syntax:
type array_value [value_dim];

• Example :
int A[10];

• The definition consists of 4 components:


– Type specified
– Identifier (name of the array)
– Operator index ([ ])
– Dimensional value inside operator [ ]

COMP6047 - Algorithm and Programming 9


Array Definition
• An illustration of array 1D
• Elements of an array indexed starting from 0

A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

COMP6047 - Algorithm and Programming 10


Array Initialization
• Array can be initialized explicitly without dimensional value
declaration
– Example:
int B[ ]={1, 2, -4, 8};
Array B has 4 elements

– Example:
int B[8]={1, 2, -4, 8};

COMP6047 - Algorithm and Programming 11


Array Initialization
- Example: int B[4] = { 1, 2, -4, 8, 9 }; //error
error in result; smaller dimensional value

• Example array initialization after definition:


int A[5];
(for i=0; i<5;i++) A[i]=0;

int B[5];
Error, why ?
B[5]={0,0,0,0,0};

COMP6047 - Algorithm and Programming 12


Accessing Arrays
• Two analogous ways of accessing an element i=2;
*(A+2) or A[2]

• A is equivalent with &A[0] or a constant pointer to the first


element of particular array

• To show A[2] on the monitor screen:


printf(“%d”,A[2]) or
printf(“%d\n”,*(A+2));

COMP6047 - Algorithm and Programming 13


Assigning Values
• Assigning value to an element
• Example : A[6] = 15; A[3] = 27;
27 15

A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

• Statement A[2] = A[3] - A[6], resulting:

12 27 15

A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

COMP6047 - Algorithm and Programming 14


Pointer Constant & Pointer Variable
• Pointer variable is a pointer that can be assigned with new
value at run-time.
• Pointer constant is a pointer that can not be assigned with
new value at run-time
• Array is Pointer Constant to its first element of the array.
Array can be filled with pointer variable.

• Example:
– int x=10, y=20;
– int *ptr; //ptr is pointer variable
– ptr = &x;
– ptr = &y;

COMP6047 - Algorithm and Programming 15


Pointer Constant & Pointer Variable
• Example:
– int x=10, y=20;
– int B[4]; // B is an Array  pointer
constant
– int *ptr; // ptr is a pointer variable
– ptr = &x; // ok
– ptr = B; // ok
– ptr++; // ok
– B = ptr; // error
– B++; // error
– B = &y; // error

• ptr = B; analogous with ptr = &B[0]; B is a pointer constant


pointing to the first element of an array.

COMP6047 - Algorithm and Programming 16


Pointer Constant & Pointer Variable
• Pointer constant can only be initialized at definition time

• Example:
int Arr1[10];
Arr1[10] = {1, 2, 3, 4, 5}; // error
Arr1 = {1, 2, 3, 4, 5}; // error
Arr1[10] = 12; // error max 9
Arr1[0] = 23; // ok

int Arr2[10] = {1, 2, 3, 4, 5}; //ok

COMP6047 - Algorithm and Programming 17


Accessing Arrays
• Accessing array using a pointer
int arr[10];
int *ptr_arr;
ptr_arr = arr; //or ptr_arr = &arr[0];

• To access certain element can be done using:


ptr_arr[i];
arr[i];
*(ptr_arr + i);
*(arr + i);
ptr_arr = ptr_arr + i; *ptr_arr;

COMP6047 - Algorithm and Programming 18


Array: Program Examples
• Example:
#include <stdio.h>
void main()
{
int i;
int list_int[10];
for (i=0; i<10; i++){
list_int[i] = i + 1;
printf( "list_int[%d] init with %d.\n", i, list_int[i]);
}
}

COMP6047 - Algorithm and Programming 19


One Dimensional Array
• C compiler does not limit number of dimensional which can be
created. Our PC memory does.
• Example Array 1D:
#include<stdio.h>

int SIZE = 5;

void main() {
int i, j;
int n[SIZE] = {15, 9, 1, 7, 5};
for( i=0 ; i<= SIZE ; i++) {
printf("%5d ", n[i]);
for ( j=1; j<=n[i] ; j++) printf("%c","*");
printf("\n");
}
}
COMP6047 - Algorithm and Programming 20
Two Dimensional Array
• Syntax 2D Array:
type name_array[row][col];
• Example:
int a[3][4];
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript
Array name
Row subscript
COMP6047 - Algorithm and Programming 21
Two Dimensional Array
• Initialization:
using rmo (row major order)
• Example: 1 2
• int b[2][2] = {1, 2, 3, 4 };
• int b[2][2] = { { 1, 2 }, { 3, 4 } }; 3 4

1 0
• int b[2][2] = { { 1 }, { 3, 4 } };
3 4

• int x[3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};


• int x[3][4] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

COMP6047 - Algorithm and Programming 22


Two Dimensional Array
• Example Array 2D:
/* Printing out array 2-D */
#include <stdio.h>
void main() {
int two_dim[3][5] = {1, 2, 3, 4, 5,
10, 20, 30, 40, 50,
100, 200, 300, 400, 500};
int i, j;
for (i=0; i<3; i++){
for (j=0; j<5; j++) printf("%6d", two_dim[i][j]);
printf("\n");
}
}

Output:
12345
10 20 30 40 50
100 200 300 400 500
COMP6047 - Algorithm and Programming 23
Three Dimensional Array
• Syntax 3D Array :
type name_array[row][col][depth];

• Example:
int x[3][2][4] = {{{1,2,3,4}, {5,6,7,8}},
{{11,12,13,14}, {15,16,17,18}},
{{21,22,23,24}, {25,26,27,28}}
};
void main() {
int x[4][3][5] = {{{1, 2, 3}, {0, 4, 3, 4}, {1, 2}},
{{9, 7, 5}, {5, 7, 2}, {9}},
{{3, 3, 5}, {2, 8, 9, 9}, {1, 2, 1}},
{{0}, {1}, {0, 1, 9}}
};
printf(“%5d”, x[2][1][3]);
}

COMP6047 - Algorithm and Programming 24


Array of Pointer
• An array filled with pointer/s
• Syntax :
type *array_name [value_dim];
• Example:
int i;
int *ptr[4];
int x=1, y=2, z=3, w=5;
ptr[0]=&x, ptr[1]=&y; ptr[2]=&z; ptr[3]=&w;
for(i=0;i<4;i++) printf("%d ",*ptr[i]);

Output : 1 2 3 5

COMP6047 - Algorithm and Programming 25


Array of Character
• Array filled with character/s

• Syntax:
char array_name[value_dim];

• Example:
char name[40];
char ss[20]={‘B’,’I’,’N’,’U’,’S’}; //20
elements
char ss[ ]= {‘B’,’I’,’N’,’U’,’S’}; // 5
elements

COMP6047 - Algorithm and Programming 26


String
• String is an array of character that ended with null character (
‘\0’ or in ASCII = 0)

• String constant or string literal is some characters written


between double quote
– Example: ”Welcome to Binus”

• String constant type is pointer constant, thus can be assigned to an


array of character :
– Example :
char name[40] = ”Amir”; //ok
name = ”Amir”; // error name is a constant
pointer
Name[40]= “Amir”; //error

COMP6047 - Algorithm and Programming 27


String
• A Constant String can be linked at compile-time:
”Hello,” ” world”
Similar to:
”Hello, world”

• Example string initialization:


char s[ ] = ”BiNus”;
Similar to :
char s[ ] = {’B’,’i’,’N’,’u’,’s’,’\0’};

• String as a data type does not known in C

COMP6047 - Algorithm and Programming 28


Char vs String
• Character in c written between single quote. Each uses one byte
of computer memory
• Example:
char ch=’A’;
char ch=65; //Ascii Similar
char ch=0x41; //Ascii

• String written in between double quote.

COMP6047 - Algorithm and Programming 29


String Manipulation
• In Standard Library Function (header file string.h) provides
functions to manipulate string:
– strlen()
Return a value of string length; excluded null char
– strcpy(s1,s2)
Copy s2 to s1
– strncpy(s1,s2,n)
Copy first n characters of s2 to s1
– strcat(s1,s2)
Adding string s2 to the end of string s1
– strncat(s1,s2,n)
Adding n characters of string s2 to the end of string s1
– strcmp(s1,s2)
Comparing the value of string s1 and s2, if similar returning 0
– etc.

COMP6047 - Algorithm and Programming 30


Program Examples
• Example: (String Manipulation)
char s1[ ] = “abcdef”;
char s2[ ] = “xyz”;

strlen(“nana”); // 4
strcmp(“nana”, “nana”) // result 0
strcpy(s1,s2); // s1 = “xyz”, s2 = “xyz”
strncpy(s1,s2,2); // s1 = “xycdef”, s2 = “xyz”
strncpy(s1,s2,4); // if n>=strlen(s2) similar with
// strcpy() s1 = “xyz”
strcat(s1,s2); // s1=“abcdefxyz”, s2=“xyz”
strncat(s1,s2,2); // s1=“abcdefxy”, s2=“xyz”

s1 = “Happy”
s2 = “New Year”

strcat( s1, s2 ) // s1= “Happy New Year”


strncat( s3, s1, 6 ) // s1= “Happy”
strcat( s3, s1 ) // s1= “Happy Happy New Year”

COMP6047 - Algorithm and Programming 31


Program Examples
• Example: (Copy String)
/* Copy string */
#include <stdio.h>
#include <string.h>
void main() {
char str1[] = "Copy a string.";
char str2[15];
char str3[15];
int i;

strcpy(str2, str1); // with strcpy()

for (i=0; str1[i]; i++) // without strcpy()


str3[i] = str1[i];
str3[i] = `\0';

/* print out str2 and str3 */


printf("The content of str2: %s\n", str2);
printf("The content of str3: %s\n", str3);
}
COMP6047 - Algorithm and Programming 32
Exercise
1. Create a program to get 10 integer values from keyboard and
store in an array. Find out:
– Max value inside the array
– Min value inside the array
– Calculate average value of the array
– Show the result to the monitor
2. Create a program in C to:
– Get a string from keyboard
– Rotate those characters
– Display the result
Example: input : KASUR
rotated : RUSAK

COMP6047 - Algorithm and Programming 33


Exercise
3. Create a program of matrix addition. Use 2D array!

4. Create a program of matrix multiplication. Use 2D array!

COMP6047 - Algorithm and Programming 34


Exercise
5. Given the following Arrays:
int A[3][4]={1, 3, 2, 4, 5, 7, 6, 8, 9,11, 12 };
int B[3][3]={{1, 2}, {3, 4, 5} ,{ 7 }};
What are the values of:
a. A[1][1] = ?
b. B[2][2] = ?
c. A[2][3] = ?
d. B[0][1] = ?
e. A[0][2] = ?

COMP6047 - Algorithm and Programming 35


Exercise
6. Given the following statements:
char str[] = ”Welcome to Binus”;
char *str = ”Welcome to Binus”;
Compare and contrast the two str identifier described above!

7. Given the following statements:


char *name[] = {”Ali”,”Ani”,”Tono”};
char name[][10] = {”Ali”,”Ani”,”Tono”};
Compare and contrast the two name identifiers above !

COMP6047 - Algorithm and Programming 36


Exercise
8. Describe some functions of <ctype.h>:
– isalpha(int c);
– isupper(int c);
– islower(int c);
– isdigit(int c);
– isalnum(int c);
– isspace(int c);
– toupper(int c);
– tolower(int c);

COMP6047 - Algorithm and Programming 37


Summary
• Pointer is a variable that store the address of another variable
• Pointer to pointer is a variable that saves another address of a
pointer
• Data saved in a certain structure to be accessed as a group or
individually. Some variables saved using the same name
distinguish by their index which called as an array
• String is an array of character that ended with null character

COMP6047 - Algorithm and Programming 38


References
• Paul J. Dietel,Harvey M. Deitel,. 2010. C : how to program.
PEAPH. New Jersey. ISBN:978-0-13-705966-9 Chapter 6 & 7
• C Programming – Pointers: http://www.exforsys.com/tutorials/c-
language/c-pointers.html
• Storing Similar Data Items: http://aelinik.free.fr/c/ch12.htm

COMP6047 - Algorithm and Programming 39


END

COMP6047 - Algorithm and Programming 40

You might also like