Document 9653865

Download Report

Transcript Document 9653865

Course Name: High Level Programming Language
Year
: 2010
Pointer
Lecture 2
Learning Outcomes
At the end of this lecture, students are capable of:
• Using pointer in C Language through an understanding of
microprocessor architecture
3
Outline Material
• Pointer and Architecture Computer
• Usage Of Pointer
• Variable Pointer
4
Pointer and Arsitektur Komputer
• Pointer is an address!!!
Uninitialized integer pointer (pointing to a random
location)
integer pointer (pointing to a variable k)
?
Null pointer (pointing to a NULL location or to a grounding location
“0”)
k
33
5
Pointer and Architecture Computer
• Function of pointer:
– It can refer to one object now and a different object later
• Generally, a pointer in C program functions to:
–
–
–
–
Return two or more value from a function
Operate on data type string
Operate on arrays and struct
Data structure that changes size (next week)
6
Usage Of Pointer
int x = 10;
int *p;
p = &x;
*p = 20;
Pointer declaration to
data type integer
& is an address operator
that takes the address of x
* dereference operator
takes 7value from p
Usage Of Pointer
int x = 10;
int *p;
p
p = &x;
p takes the address of8 the variable x
10
x
Usage Of Pointer
int x = 10;
int *p;
p
p = &x;
*p = 20;
*p is the value inside the
address p
9
20
x
Conclusions
• Pointer variable contains address, not data value, always
remember that!
• Pointer refers only to one particular object at one time,
though later, it can be altered to different object.
• Dereference Pointer is used to access a content of a
particular memory allocation.
10
Topic For Next Week
• Variable Pointer
– Assignment: Read book of “CppEssentials.pdf” chapter 5 pages 65 until 79.
– Do the following exercises (taken from “exercises” page 80 of book
“CppEssentials.pdf”):
1.
Define a function to input a list of names and store them as dynamically-allocated
strings in an array, and a function to output them:
void ReadNames (char *names[], const int size);
void WriteNames (char *names[], const int size);
11
Topic For Next Week
Continued.
Write another function which sorts the list using bubble sort:
void BubbleSort(char *names[], const int size);
Bubble sort involves repeated scans of the list, where during each scan adjacent items are compared and
swapped if out of order. A scan that involves no swapping indicates that the list is sorted.
12
Topic For Next Week
2. Rewrite the following function using pointer arithmetic:
char* ReverseString (char *str)
{
int len = strlen(str);
char *result = new char[len + 1];
for (register I = 0; I < len; ++i)
result[i] = str[len – i – 1];
result[len] = ‘\0’;
return result;
}
13