Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатика
ИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханика
ОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторика
СоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансы
ХимияЧерчениеЭкологияЭкономикаЭлектроника

Pointer Arithmetic

Читайте также:
  1. Operators. Expressions use familiar arithmetic operators and precedence rules.

Pointer arithmetic is not the same as integer arithmetic, because the outcome depends on the size of the object pointed to. For example, suppose that an int is represented by 4 bytes. Now, given

 

char *str = "HELLO";

int nums[] = {10, 20, 30, 40};

int *ptr = &nums[0]; // pointer to first element

 

str++ advances str by one char (i.e., one byte) so that it points to the second character of "HELLO", whereas ptr++ advances ptr by one int (i.e., four bytes) so that it points to the second element of nums. Figure below illustrates this diagrammatically.

 

 

It follows, therefore, that the elements of "HELLO" can be referred to as *str, *(str + 1), *(str + 2), etc. Similarly, the elements of nums can be referred to as *ptr, *(ptr + 1), *(ptr + 2), and *(ptr + 3).

In turns out that an array variable (such as nums) is itself the address of the first element of the array it represents. Hence the elements of nums can also be referred to using pointer arithmetic on nums, that is, nums[i] is equivalent to *(nums + i). The difference between nums and ptr is that nums is a constant, so it cannot be made to point to anything else, whereas ptr is a variable and can be made to point to any other integer. Listing 4 shows how the HighestTemp function (shown earlier in Listing 2) can be improved using pointer arithmetic.

 

Listing 4

int HighestTemp (const int *temp, const int rows, const int columns) {

int highest = 0;

for (register i = 0; i < rows; ++i)

for (register j = 0; j < columns; ++j)

if (*(temp + i * columns + j) > highest)

highest = *(temp + i * columns + j);

return highest;

}

 

Instead of passing an array to the function, we pass an int pointer and two additional parameters which specify the dimensions of the array. In this way, the function is not restricted to a specific array size. The expression *(temp + i * columns + j) is equivalent to temp[i][j] in the previous version of this function.

 

References

A reference introduces an alias for an object. The notation for defining references is similar to that of pointers, except that & is used instead of *. For example,

 

double num1 = 3.14;

double &num2 = num1; // num is a reference to num1

 

defines num2 as a reference to num1. After this definition num1 and num2 both refer to the same object, as if they were the same variable. It should be emphasized that a reference does not create a copy of an object, but merely a symbolic alias for it. Hence, after

 

num1 = 0.16;

 

both num1 and num2 will denote the value 0.16.

A reference must always be initialized when it is defined: it should be an alias for something. It would be illegal to define a reference and initialize it later.

 

double &num3; // illegal: reference without an initializer

num3 = num1;

 

The most common use of references is for function parameters. Reference parameters facilitate the pass-by-reference style of arguments, as opposed to the pass-by-value style which we have used so far. To observe the differences, consider the three swap functions in Listing 5.

 

Listing 5

void Swap1 (int x, int y) { // pass-by-value (objects)

int temp = x;

x = y;

y = temp;

}

void Swap2 (int *x, int *y) { // pass-by-value (pointers)

int temp = *x;

*x = *y;

*y = temp;

}

void Swap3 (int &x, int &y) { // pass-by-reference

int temp = x;

x = y;

y = temp;

}

 

Although Swap1 swaps x and y, this has no effect on the arguments passed to the function, because Swap1 receives a copy of the arguments. What happens to the copy does not affect the original.

Swap2 overcomes the problem of Swap1 by using pointer parameters instead. By dereferencing the pointers, Swap2 gets to the original values and swaps them.

Swap3 overcomes the problem of Swap1 by using reference parameters instead. The parameters become aliases for the arguments passed to the function and therefore swap them as intended.

Swap3 has the added advantage that its call syntax is the same as Swap1 and involves no addressing or dereferencing. The following main function illustrates the differences:

 

int main (void) {

int i = 10, j = 20;

Swap1(i, j); cout << i << ", " << j << '\n';

Swap2(&i, &j); cout << i << ", " << j << '\n';

Swap3(i, j); cout << i << ", " << j << '\n';

}

 

When run, it will produce the following output:

10, 20

20, 10

10, 20

 

Lab Overview

2.1. Read the theory and try Control Exercises.

2.2. Develop the algorithm flowchart to solve a problem according to individual case from the Table below.

2.3. Write the program code according to the developed algorithm using dynamic arrays, user-defined functions and pointers/references.

2.4. Debug the program, run it and make screenshots.

2.5. Prepare the Lab Report according to the required structure.

 

# Array type Task
1. 2D, float Calculate the number of items greater than 0
2. 2D, double Calculate the sum of pair items
3. 2D, int Calculate the number of negative items
4. 2D, unsigned int Calculate the sum of diagonal items
5. 2D, float Substitute 0-items by 1 and output array in reverse order
6. 2D, double Find an average value of array items
7. 2D, int Find maximum and minimum values in an array
8. 2D, unsigned int Calculate an average of diagonal items
9. 2D, float Divide array items by 10 and output items greater than 0.5
10. 2D, double Calculate the sum of odd items
11. 2D, int Calculate the number of items greater than 5
12. 2D, unsigned int Substitute items greater than 5 by 1, all the rest – by 0
13. 2D, float Calculate a per-element sum of two arrays of the same type and size
14. 2D, double Output array with greater sum of elements (use two arrays for comparison)
15. 2D, int Build a transposed array for a given one
16. 2D, unsigned int Create 2D array of defined size from an inputted vector
17. 2D, float Calculate a per-element multiplication of two arrays of the same type and size
18. 2D, double Output array with greater average value of elements (use two arrays for comparison)
19. 2D, int Output main diagonal elements which may be divided by 2 without remainder
20. 2D, unsigned int Calculate a number of elements equal to 1, 2, …, 9 in an array

 


Дата добавления: 2015-10-29; просмотров: 120 | Нарушение авторских прав


Читайте в этой же книге: ТЕМА 3. Применение операционных усилителей | Operator Precedence | Simple Type Conversion | Inline Functions | Introduction to Strings |
<== предыдущая страница | следующая страница ==>
Multidimensional Arrays| Introducing Structures

mybiblioteka.su - 2015-2024 год. (0.008 сек.)