Pointers in C programming - SOICT - Data structures & Algorithms - IT3010E
Pointers in C programming - SOICT - Data structures & Algorithms - IT3010E
7 8
2. Pointer Variables 2. Pointer Variables
• A pointer is a variable that stores the address of something else. A pointer is a variable that holds
the address of something else. MEMORY
• Declare pointer: Address
Pointer points to the data. 0
type *pointer_name; 1
int x = 123; 2
Use asterisk ( * ) to show this is pointer //Declare an int, assign the value of 123
x 3 123
• There are many types of variables with different sizes, so there are int *ptr;//declare a pointer to an int 4
also many types of pointers. (Example: int pointer to point to a 5
//same as int* ptr;
variable or function of type int).
...
...
//or int * ptr;
Example:
int *countPtr; //This is read as “countPtr is a pointer to an int” ptr = &x; //assign ptr the memory address of x
ptr 345 3
double *tPtr; //This is read as “tPtr is a pointer to a double”
346
• A Pointer may be initialized to 0, NULL, or an address.
Address of x is value of ptr 347
• NULL is a Symbolic constant defined in <iostream> to represent the
value 0.
• A Pointer that is assigned 0 or NULL points to nothing. 9 10
11 12
Pointers to anything Contents
1. Getting the Address of a Variable
x some int 2. Pointer Variables
int *x; 3. The Relationship Between Arrays and Pointers
int **y; 4. Pointer Arithmetic
y some *int some int
5. Initializing Pointers
6. Pointers as Function Parameters
double *z;
z some double 7. Pointer to constants
8. Dynamic Memory Allocation
13 14
• Pointer can be used as an array name: *ptr *(ptr+2) *(ptr+4) ptr[i] ~ value of a[i]
cout << ptr[1]; //displays 7 (value of a[1]) a[0] a[1] a[2] a[3] a[4]
#include <iostream>
Write C++ program to print address of each element in a 1D-array:
using namespace std;
#include <iostream>
int main()
using namespace std;
int main() Result in DevC { int A[ ] = {5, 10, 12, 15, 4};
5 10 12 15 4 65516 5
cout<<"Address Contents\n";
65518 10
65520 12 for (int i=0; i < 5; i++) &ptr[i] : address of element A[i]
65522 15 cout<<&ptr[i]<<“ “<<ptr[i]<<endl; ptr[i] : value of element A[i]
65524 4 }
start_address=6487536
Example: Write C++ program to print address of each element in a 1D-array Example
#include <iostream>
Write C program to print address of each element in a 1D-array:
using namespace std;
int main()
#include <stdio.h>
{ int A[ ] = {5, 10, 12, 15, 4};
int main()
cout<<"Address Contents\n";
&A[i] : address of element A[i] { int A[ ] = {5, 10, 12, 15, 4};
for (int i=0; i < 5; i++)
A[i] : value of element A[i] printf("Address Contents\n");
cout<<&A[i]<<“ “<<A[i]<<endl;
for (int i=0; i < 5; i++)
&A[i] : address of element A[i]
printf("%8d %5d\n", &A[i], A[i]); A[i] : value of element A[i]
cout<<"Address Contents\n"; A+i : address of element A[i]
for (int i=0; i < 5; i++)
*(A+i) : value of element A[i]
cout<<A+i<<“ “<<*(A+i)<<endl;
printf("Address Contents\n");
for (int i=0; i < 5; i++) A+i : address of element A[i]
/* print the address of 1D array by using pointer */
int *ptr = A;
printf("%8d %5d\n", A+i, *(A+i)); *(A+i) : value of element A[i]
cout<<"Address Contents\n"; ptr+i : address of element A[i]
for (int i=0; i < 5; i++) *(ptr+i): value of element A[i]
/* print the address of 1D array by using pointer */
cout<<ptr+i<<“ “<<*(ptr+i)<<endl;
int *ptr = A;
printf("Address Contents\n");
cout<<"Address Contents\n"; ptr+i : address of element A[i]
for (int i=0; i < 5; i++) &ptr[i] : address of element A[i] for (int i=0; i < 5; i++)
*(ptr+i) : value of element A[i]
cout<<&ptr[i]<<“ “<<ptr[i]<<endl; ptr[i] : value of element A[i] printf("%8d %5d\n", ptr+i, *(ptr+i));
}
}
Printing an array Printing an array
void print_array(int a[], int len) {
for (int i=0;i<len;i++)
cout << "[" << i << "] = "
<< a[i] << endl;
}
21 22
#include <iostream>
using namespace std;
const int MAX = 100;
Arrays as Function Arguments
• When an entire array is passed to a function, it is not passed by value, but passed by
int main()
reference.
{
int numbers[MAX]; // Array of integers – Imagine the CPU time and memory that would be necessary if a copy of a
int SIZE; // Size of the array 10,000-element array were created each time it was passed to a function!
int count; // Counter variable Instead, only the starting memory address of the array is passed.
int *ptr = numbers; Changes made to array in a function are reflected in actual array in calling function
cout << “Size of the array = “; cin>>SIZE;
for (count = 0; count < SIZE; count++)
// Get a value to store in numbers[count].
// Use pointer notation instead of subscripts.
(1) cin >> ptr[count];
cout << "Here are the numbers you entered:\n"; for (int index=0; index < ARRAY_SIZE; index++)
for (count = 0; count < SIZE; count++) cout<<numbers[index]<<“ “;
// Display a value of the array.
// Use pointer notation instead of subscripts.
(2) cout << ptr[count];
cout << endl;
return 0; for (int index=0; index < size; index++)
} 27 nums[index]*=2; 28
Exercise Exercise: Array version
Write a program that includes the following functions:
Input values for an array
Increase all values of the array by 2
Print out an array
You should use pointers to access the array. The array is
passed as function parameters
Array version:
void input_array(int a[], int len);
void change_array(int a[], int len);
void print_array(int a[], int len);
Pointer version:
void input_arrayP(int *a, int len);
void change_arrayP(int *a, int len);
void print_arrayP(int *a, int len);
29 30
31 32
Contents 6. Pointers as Function Parameters
• A pointer can be a parameter
1. Getting the Address of a Variable
• Works like reference variable to allow change to argument from within function
2. Pointer Variables • Requires:
– asterisk * on parameter in prototype and heading:
3. The Relationship Between Arrays and Pointers void getNum(int *ptr); //ptr is pointer to an int
4. Pointer Arithmetic – asterisk * in body to deference the pointer (~access the object that the pointer points
to):
5. Initializing Pointers cin >> *ptr;
– address as argument to the function:
6. Pointers as Function Parameters getNum(&num); //pass address of num to function getNum
7. Pointer to constants
8. Dynamic Memory Allocation
33 34
Example 1 Example 2
void swap(int *x, int *y){ void swap(int x, int y){ // This program uses two functions that accept addresses of
//swap the contents pointed int temp = x; // variables as arguments.
//by pointers x and y: x = y; #include <iostream>
int temp = *x; y = temp; using namespace std;
*x = *y; }
*y = temp; int main(){ // Function prototypes
} int num1 = 2, num2 = 3; void getNumber(int *);
int main(){ void doubleValue(int *);
swap(num1, num2);
int num1 = 2, num2 = 3; }
int main()
//pass address of num1 and num2
{ int number;
//to function swap:
swap(&num1, &num2);
// Call getNumber and pass the address of number.
}
getNumber(&number);
• In pass-by-reference: the function
receives a direct link to the original // Call doubleValue and pass the address of number.
variable, so any changes made within doubleValue(&number);
the function do modify the original.
• In pass-by-value: a copy of the // Display the value in number.
variable's value is sent to a function, so cout << "That value doubled is " << number << endl;
any changes made to it within the return 0;
function do not affect the original 35
} 36
variable.
Example 2 Contents
//***************************************************************
// Definition of getNumber. The parameter, input, is a pointer. * 1. Getting the Address of a Variable
// This function asks the user for a number. The value entered *
// is stored in the variable pointed to by input. * 2. Pointer Variables
//***************************************************************
#include <stdio.h>
int main() {
int var = 10;
//Pointer to int
int *ptr1 = &var;
// Pointer to pointer (double pointer)
int **ptr2 = &ptr1;
printf("var: %d\n", var);
printf("*ptr1: %d\n", *ptr1);
printf("**ptr2: %d", **ptr2);
return 0;
39 40
}
6. Pointer to pointer (double pointer) Contents
Declaration: A double pointer can be declared similar to a single pointer. The 1. Getting the Address of a Variable
difference is we have to place an additional ‘*’ before the name of the pointer.
type **name; 2. Pointer Variables
Initialization: The double pointer stores the address of another pointer to the 3. The Relationship Between Arrays and Pointers
same type.
name = &single_ptr; // After declaration
4. Pointer Arithmetic
type **name = &single_ptr; // With declaration
5. Initializing Pointers
Deferencing: To access the value pointed by double pointer, we have to use the
dereference operator * two times. 6. Pointers as Function Parameters
*name; //Gives the address of the single pointer 7. Pointer to constants
**name; //Gives the value of the variable it points to
8. Dynamic Memory Allocation
41 42
43 44
Constant Pointers Constant Pointers to Constants
• A constant pointer is a pointer that is initialized with an address, • A constant pointer to a constant is:
and cannot point to anything else. – a pointer that points to a constant
• Example: – a pointer that cannot point to anything except what it is
int value = 22; pointing to
Example:
* const indicates that ptr is a constant pointer int value = 22;
45 46
47
Memory Allocation Conceptual View of Memory
51
Allocating memory using “new” 8. Dynamic Memory Allocation
• Uses malloc operator to allocate memory:
C
double *iptr;
int *p; new returns the address to the iptr = (double*) malloc(sizeof(double));
“start” of the memory it allocated
p = new int[7]; //allocate mem for 7 integers • To allocate array:
//p is assigned 8002 8002 p[0] int *arrayPtr = (int*) malloc(100 * sizeof(int));
8006 p[1]
• Uses new operator to allocate memory:
8010 p[2]
C++
p[0] = *(p) = *(p+0) = ? double *iptr;
8014 iptr = new double;
p[1] = *(p+1) = ?
• To allocate array:
8018
p[2] = *(p+2) = ? int *arrayPtr = new int[100];
8022 • To access array:
8026 for(i=0;i<100;i++)
arrayPtr[i]=i*i; //or *(arrayPtr+i)=i*i;
• Program will terminate if not enough memory available to allocate 54
int a;
• Use delete to free dynamic memory:
C++
a
delete iptr;
• Use [] to free dynamic array:
p = &a;
delete [] arrayPtr; NO ONE HAS ACCESS TO THIS MEMORY 100 integers