0% found this document useful (0 votes)
8 views

[Week 11] Intermediate Programming 2

Uploaded by

cbd11218
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

[Week 11] Intermediate Programming 2

Uploaded by

cbd11218
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

BASIS AND PRACTICE IN PROGRAMMING

Intermediate
Programming 2

INSTRUCTOR YOUNGHOON KIM


Recap

Pointers
- Two different usages of '*'
int*  pointer type
*p  dereference operator (value-of operator)
- Address-of operator '&'

Pointer Usages
- We must initialize pointers before using them.
- Without pointers initializations, we will have unaware accesses to garbage addresses.
Pointers
as Return Values
Pointers as a Return Type

Functions are allowed to return pointers:


int* max_pointer(int *a, int *b) {
if (*a > *b)
return a;
else
return b;
}

Return type of above function is int*.


- The max_pointer function uses values in the caller directly and returns an address.

You CANNOT return a pointer of a local variable.


- Local variables of functions are not accessible after returning.
Pointers as a Return Type

A call of the max function:


int num1 = rand() % 100, num2 = rand() % 100;
int *max = max_pointer(&num1, &num2);
printf("num1: %d\n", num1);
printf("num2: %d\n", num2);
printf("max: %d\n", *max); call by value

int max_value, i, j;

After the call, max points to either num1 or num2. max_value = max(i, j);

num1

max 10

20
num2
Pointers as a Return Type DEMO

Two different functions for obtaining the max value.


- Assigning a new value to the returned address will affect the original variable.

int main() {
#include <stdio.h>
srand(0);
#include <stdlib.h>
int num1 = rand() % 100, num2 = rand() % 100;
printf("num1: %d\n", num1);
int max(int a, int b) {
printf("num2: %d\n", num2);
if (a > b)
printf("max: %d\n\n", max(num1, num2));
return a;
else
int *max = max_pointer(&num1, &num2);
return b;
int max_value = *max;
}
*max = 0;
int* max_pointer(int *a, int *b) {
printf("num1: %d\n", num1);
if (*a > *b)
printf("num2: %d\n", num2);
return a;
printf("max: %d\n", *max);
else
printf("max: %d\n", max_value);
return b;
return 0;
}
}
Pointers for Multiple Returns

Pointers can be used for multiple return values.


Example: scanf

int main()
{
int num1, num2, num3;
scanf("%d %d %d", &num1, &num2, &num3);
printf("%d %d %d", num1, num2, num3);
}

scanf can be called with multiple variables and the results are
stored in each variable.
- You can understand it as returning multiple values from a function call.
Exercise: min_max function DEMO

Make a function that returns the min and max value of an array.
- You can pass pointers to functions to store the return values.

void min_max(int number[], int size, <parameters>)


{

<Source Code>

}
Exercise: min_max function (Solution) DEMO

Make a function that returns the min and max value of an array.
- You can pass pointers to functions to store the return values.

void min_max(int number[], int size, int* min, int* max)


{
*min = number[0], *max = number[0];
for(int i=0; i<size; i++) {
if(number[i] < *min)
*min = number[i];
if(number[i] > *max)
*max = number[i];
}
}
Exercise: min_max function (Solution) DEMO

Make a function that returns the min and max value of an array.
- You can pass pointers to functions to store the return values.

int main()
{
int num[10];
init_array(num, 10); // a function for initializing an array
print_array(num, 10); // a function for printing an array
int min, max;
min_max(num, 10, &min, &max);
printf("min: %d, max: %d\n", min, max);
}

.
BASIS AND PRACTICE IN PROGRAMMING

Intermediate
Programming 2

INSTRUCTOR YOUNGHOON KIM


Pointers and Arrays
Pointer Arithmetic

Pointer arithmetic is one of the powerful features of C .

This allows us to easily manipulate addresses directly.


- C allows us to perform arithmetic (addition and subtraction) on pointers to array elements.
- If p points to an element of an array a, the other elements of a can be accessed by performing
pointer arithmetic on p.
Pointer Arithmetic Example

Example for a machine with 4-byte integers:


- int v[5] has been defined and its first element is at location 3000 in memory.
- Pointer vPtr has been initialized to point to v[0].
- Addresses of elements in an array v can be illustrated as below:
Pointer Arithmetic Example

Example for a machine with 4-byte integers:


- In conventional arithmetic, 3000 + 2 yields the value 3002, but not for a pointer.
- The meaning of "+" with a pointer is moving the pointer to a "next element".
- So, when vPtr points to v[0], below code would produce 3008. ( 3000 + 2 x 4)
Original address + (operand) x (the size of the object)

vPtr += 2; // If vPtr pointed to v[0], it now points to v[2].


Pointer Arithmetic

More examples:

vPtr -= 4; // If vPtr pointed to v[4], it now points to v[0]


vPtr++; // increments vPtr to point to the next array location
++vPtr;
vPtr--; // decrements vPtr to point to the previous array location
--vPtr;

- A pointer may be incremented (++) or decremented (--).


- An integer may be added to a pointer (+ or +=).
- An integer may be subtracted from a pointer (- or -=).

The meaning of "+" with a pointer is moving the pointer to a "next element".
The meaning of "-" with a pointer is moving the pointer to a "previous element".
Pointer Arithmetic with Graphical Explanation

'+' example

int a[10], *p, *q;


p = &a[2];
q = p + 3;
p += 6;
Pointer Arithmetic with Graphical Explanation

'-' example

int a[10], *p, *q;


p = &a[8];
q = p - 3;
p -= 6;
Using Pointers for Array Processing

Example: A loop that sums the elements of an array a


- Pointer arithmetic allows us to visit the elements of an array by repeatedly incrementing a
pointer variable.
- Check the usage of increment operator in the below code.
CHECKPOINT: The initial address is set with '&a[0]' and the last one with '&a[N]'.

#define N 10

int a[N]={1,2,3,4,5,6,7,8,9,10}, sum, *p;

sum = 0;
for (p = &a[0]; p < &a[N]; p++)
sum += *p;
Relationship between Pointers and Arrays

The name of an array can be used as a pointer to the first element in the array.
- An array name can be thought of as a constant pointer.

int a[5] = {1,2,3,4,5};


int *aPtr, num; // num is an integer variable!
aPtr = a; // or, equivalently, 'aPtr = &a[0];'
num = *(aPtr + 3); // referencing 4th element in a, which is a[3]

- We can set aPtr equal to the address of the first element in array a as above code.
- '3' in the 4th line is an offset, and the value is identical to the array index.
Note that 'aPtr + 3' is equivalent to '&a[3]' when the pointer points to the array's first element.
- This notation is referred to as pointer/offset notation.
Using an Array Name as a Pointer

The name of an array can be used as a pointer to the first element in the array.
- An array name can be thought of as a constant pointer.

int a[5] = {1,2,3,4,5};


*a = 7; // storing 7 in a[0]
*(a+1) = 12; // storing 12 in a[1]
//a += 3; // ERROR!!!

- a + i is the same as &a[i]. Also, *(a+i) is equivalent to a[i].


- The preceding statement cannot modify the array name.
a still points to the first element in the array after the execution of above code.
- Attempting to modify the value of the array name with pointer arithmetic is invalid.

- CHECKPOINT: Explain the difference between *(a+1) and *a + 1.


Warning: Pointer Arithmetic

The addition and subtraction of pointers would easily go outside the valid
memory range.
- Compilers do not check the valid boundary.
- It will cause a memory-related error.

int a[5] = {1,2,3,4,5};


*(a+10) = 12; // Accessing outside of the array
for(int i=0; i<10; i++) { // Accessing outside of the array, also.
a[i] = 0;
}
Using Pointers for Array Processing 2 DEMO

Example 2: A loop that sums the elements of an array a


- We can use the array's name as a pointer.
- CHECKPOINT: The initial address is set with 'a' and the last one with 'a+N'.

#define N 10

int a[N]={1,2,3,4,5,6,7,8,9,10}, sum, *p;

sum = 0;
for (p = a; p < a+N; p++)
sum += *p;
Using an Array Name as a Pointer Examples

Original version:
for (p = &a[0]; p < &a[N]; p++)
sum += *p;

Simplified version 1:
for (p = a; p < a + N; p++)
sum += *p;

Simplified version 2:
p = a;
while (p < a+N)
p++;
Exercise: min_max function (Pointer Arithmetic) DEMO

Make a function that returns the min and max value of an array.
- You must use pointer arithmetic while traversing the array.

void min_max(int number[], int size, <parameters>)


{

<Source Code>

}
Exercise: min_max function (Pointer Arithmetic, Solution) DEMO

Make a function that returns the min and max value of an array.
- You must use pointer arithmetic while traversing the array.

void min_max(int number[], int size, int* min, int* max)


{
*min = number[0], *max = number[0];
for(int* p = &number[0]; p <= &number[size-1]; p++) {
// for(int* p = number; p < number+size; p++) {
if(*p < *min)
*min = *p;
if(*p > *max)
*max = *p;
}
}
Exercise: min_max function (Pointer Arithmetic, Solution) DEMO

Make a function that returns the min and max value of an array.
- You must use pointer arithmetic while traversing the array.

int main()
{
int num[10];
init_array(num, 10); // a function for initializing an array
print_array(num, 10); // a function for printing an array
int min, max;
min_max(num, 10, &min, &max);
printf("min: %d, max: %d\n", min, max);
}
Reading Materials

Pointer Arithmetic
- When an integer is added to or subtracted from a pointer, the pointer is not incremented or
decremented simply by that integer, but by that integer times the size of the object to which the
pointer refers. The number of bytes depends on the object’s data type.

- If an integer is stored in 2 bytes of memory, then the preceding calculation would result in
memory location 3004 (3000 + 2 * 2).

- When performing pointer arithmetic on a character array, the results will be consistent with
regular arithmetic, because each character is 1 byte long.

.
BASIS AND PRACTICE IN PROGRAMMING

Intermediate
Programming 2

INSTRUCTOR YOUNGHOON KIM


Arrays of Pointers
Arrays of Pointers

Arrays may contain pointers.


- A common use of an array of pointers is to form an array of strings.
- Simply as a string array

Consider the case with storing string in an array.


- Using a two-dimensional array of characters with one string per row is one option.
- Example code for storing planet names in a two-dimensional array:

char planets[9][8] = {"Mercury", "Venus", "Earth",


"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto"};
Arrays of Strings

A problem with the below code:


- The planets array contains a fair bit of wasted space
(extra null characters):

char planets[9][8] = {"Mercury", "Venus", "Earth",


"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto"};

- CHECKPOINT: Why are the latter parts of the array


initialized with null characters?
Arrays of Strings

Handling a mixture of long and short strings:


- Most collections of strings will have a mixture of long strings and short strings.
- What we need is a ragged array, whose rows can have different lengths.
- We can simulate a ragged array in C by creating an array whose elements are pointers to strings:

char *planets[9] = {"Mercury", "Venus", "Earth",


"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto"};

- '[9]' in the definition indicates an array of 9 elements.


- 'char *' in declaration indicates that each element of array is of type "pointer to char."
A string in C is a pointer to its first character.
Arrays of Strings

This small change has a dramatic effect on how


planets is stored as below.

char *planets[9] = {"Mercury", "Venus", "Earth",


"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto"};

- Each pointer points to the first character of its


corresponding string.
- Even though the planets array is fixed in size, it provides
access to character strings of any length.
- WARNING: Additional memory is needed for pointers.
- CHECKPOINT: We cannot modify strings in this string array.
Why?
A String Array DEMO

An example for storing strings:


- Two ways of it will be introduced in the demo.
- CHECKPOINTs will also be handled.

char planets_array[9][8] = {"Mercury", "Venus", "Earth",


"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto"};
char *planets_ptr[9] = {"Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto"};

for(int i=0; i<9; i++) {


printf("%s\n", planets_ptr[i]);
printf("%s\n", planets_array[i]);
}

You might also like