Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
ab11167
11 views
16 slides
Aug 27, 2024
Slide 1 of 16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
About This Presentation
### Pointers in Programming: An Overview
#### Introduction
Pointers are a fundamental concept in programming, particularly in languages like C, C++, and others that provide low-level memory management capabilities. A pointer is a variable that stores the memory address of another variable. This mi...
### Pointers in Programming: An Overview
#### Introduction
Pointers are a fundamental concept in programming, particularly in languages like C, C++, and others that provide low-level memory management capabilities. A pointer is a variable that stores the memory address of another variable. This might seem a bit abstract at first, but pointers are crucial for understanding how data is stored and manipulated in a computer's memory. They enable efficient array handling, dynamic memory allocation, and the creation of complex data structures like linked lists, trees, and graphs.
#### Memory and Addresses
To understand pointers, it is essential to have a basic grasp of how memory is organized in a computer. A computer's memory can be thought of as a large array of bytes, each with its own unique address. These addresses are typically represented as hexadecimal numbers. When you declare a variable in a program, the compiler allocates a specific amount of memory for that variable, depending on its type (e.g., 4 bytes for an integer on many systems).
For example:
```c
int x = 10;
```
Here, the compiler allocates memory to store the integer value `10` and assigns a specific address to this memory location. The variable `x` represents the value stored at this memory address.
#### What is a Pointer?
A pointer is a variable that holds the address of another variable. Instead of storing a value directly, a pointer stores the location of a value. This concept can be a bit tricky because it introduces a level of indirection. Here’s an example to clarify:
```c
int x = 10;
int *p = &x;
```
In this code, `x` is an integer variable, and `p` is a pointer to an integer. The `&x` operator is used to get the address of the variable `x`, which is then assigned to the pointer `p`. Now, `p` doesn’t hold the value `10` but rather the memory address of `x`.
#### Dereferencing Pointers
To access the value stored at the address that a pointer holds, you use the dereferencing operator `*`. Dereferencing a pointer means accessing the value located at the address the pointer holds. Continuing with the previous example:
```c
int value = *p;
```
Here, `*p` gives you the value stored at the address that `p` points to, which is `10` in this case. The variable `value` will now also hold the value `10`.
#### Why Use Pointers?
Pointers provide several benefits:
1. **Dynamic Memory Allocation:** Pointers are essential for dynamic memory allocation, which allows you to allocate memory during runtime. This is particularly useful when the size of the data is not known beforehand.
```c
int *p = (int*)malloc(sizeof(int));
```
The above line allocates memory dynamically for an integer and returns a pointer to that memory location.
2. **Efficiency in Array and String Handling:** Pointers allow efficient handling of arrays and strings. Instead of copying entire arrays or strings, you can simply pass a pointer to the beginning of the array or string to functions.
Size: 97.36 KB
Language: en
Added: Aug 27, 2024
Slides: 16 pages
Slide Content
ENGR-UH 1000 Lab 8 Pointers
Pointers in C++ Addresses in memory Programs can manipulate addresses directly & expr Evaluates to the address of the location expr evaluates to * expr Evaluates to the value stored in the address expr evaluates to
Parameter Passing in C++ Actual parameters are values void swap (int a, int b) { int tmp = b; b = a; a = tmp; } int main (void) { int i = 3; int j = 4; swap (i, j); … } The value of i (3) is passed, not its location! swap does nothing
Parameter Passing Using Pointers void swap (int *a, int *b) { int tmp = *b; *b = *a; *a = tmp; } int main (void) { int i = 3; int j = 4; swap (&i, &j); cout << i << j << endl; } The value of &i is passed, which is the address of i
Pointers and Arrays The name of the array variable is a pointer to the first element of that array! int arr[5] = {1, 2, 3, 4, 5}; // initialize array int *ptr = arr; // set pointer to array // You can now use ptr and arr interchangeably! cout << ptr[2] << ‘\n’; // What will this print?
Pointers and Arrays The same relationship goes backwards as well! int arr[5] = {1, 2, 3, 4, 5}; // initialize array cout << arr << ‘\n’; // what will this print? // in fact, when we use square brackets, we actually do the following: cout << arr[3] << ‘\n’; // this is the same thing as: cout << *(arr + 3) << ‘\n’; // this works because array variable names are // pointers themselves!
Dynamic Memory Allocation int *iPtr; // declaring a pointer variable iPtr = new int(100); // dynamic allocation of a single intege double *dPtr; // declaring a pointer variable dPtr = new double[20]; // dynamic allocation of an array delete iPtr; // dynamic de-allocation delete[] dPtr; // dynamic de-allocation of an array
Pointers To Pointers Graphically, the construct of a pointer to pointer can be depicted as shown below: pointer_one is the first pointer, pointing to the second pointer, pointer_two and finallypointer_two is pointing to a normal variable num that hold integer 10. char ch = ‘A’; char **secondPtr, *firstPtr; // declare first and second pointers firstPtr = &ch; // store address of ch in firstPtr secondPtr = &firstPtr; // store the address of firstPtr in secondPtr **secondPtr = ‘B’; // store ‘B’ in ch
Exercise 1 Assuming that the statement int x, *ptr=&x; places the variable x into memory at address 8688 and the ptr variable at 8684. Write down the output you expect for the following code: x=130; cout << x << endl; cout << ptr << endl; x=131; cout << x << endl; cout << &ptr << endl; x=132; cout << &x << endl; cout << ptr << endl; x=133; cout << &x << endl; cout << *ptr << endl; if(x != *ptr) cout << “Hello1” << endl; else cout << “Hello2” << endl;
Exercise 2 Identify the errors: #include <iostream> void main() { int x, y=131, *ptr; x=132; y=*ptr; cout << x << endl; cout << y << endl; return 0; } #include <iostream> void main() { int x,y=131, *ptr; x=132; ptr=&x; &y=ptr; cout << x << endl; cout << y << endl; return 0; } #include <iostream> void main() { int x=131,y, *ptr=y; y=132; *ptr=x; cout << x << endl; cout << y << endl; return 0; }
Example 3 Write a program that calls a function to swap two characters and print them in the new form using call by pointer.
Example 4 Write a function that receives a pointer to a character string and a character. The function should return the number of times that the character occurred in the string. Note that a string is an array of characters terminated by the special character ‘\0’. Assume that the function has the following prototype: int char_count (char *ptr, char c)
Example 5 Write a program that reads a data file that contains the time (second) and coordinates of the position of a robot that is roaming in unknown space. The first row stores the number of readings. Each subsequent line includes the time, the x coordinate, and the y coordinate for the robot. The program should determine the times when the robot comes inside a circle centered at the origin with a radius R (entered by the user). Use dynamic memory allocation to create run-time arrays for storing the time, x coordinate, and y coordinate.
Example 6 Write a program that dynamically resize an array to a bigger size. The program creates an array of an arbitrary size (specified by the user). Then the user may extend the array to a bigger size (this involves creating a temporary array with larger size, copying the values of the elements, and adding new values into the extension cells). Print the new array to the user to confirm the functionality.
Example 7 G O L F \0 H O C K E Y \0 F O O T B A L L \0 C R I C K E T \0 S H O O T I N G \0 Write a program that uses double pointer to create an array of strings to store the names of sports as shown in the following figure. Print these strings on the output screen on separate lines. Make sure to deallocate the memory before terminating the program. sports