T10 - Pointers
T10 - Pointers
T10 - Pointers
Tutorial 10 – Pointers
Q1. Declare an integer variables x = 1 and an array y[5] = {10, 20, 30, 40, 50}, and two integer pointers xPtr and
yPtr that point to x and y respectively. Write your code to determine the following:
(a) What are the address of x and y?
(b) What are the values stored in xPtr and yPtr?
(c) What is the meaning of *xPtr and *yPtr?
(d) What is the difference between (*yPtr + 2) and *(yPtr + 2)?
(e) What is the following code segment doing?
xPtr = yPtr + 2;
(*xPtr)++;
(*yPtr)++;
Q2. Write a function swapInteger() which has two integer pointers a and b as parameters. The function
interchanges the integers that are pointed to by a and b. The function prototype of swapInteger() is as follow:
void swapInteger(int *, int *);
Use the main function below to demonstrate the use of swapInteger().
int main(){
int x = 2, y = 5;
return 0;
}
Sample result:
Before swapping:
x is: 2 Think first:
y is: 5 In the function, swap the pointers? Or swap
After swapping: the values pointed to by the pointers?
x is: 5
y is: 2
#include <iostream>
using namespace std;
int main(){
const int arraySize = 10;
return 0;
}
#include <iostream>
using namespace std;
int main() {
char *buffer = new char [100]; // reserve 100 characters
char *word[10] = {}; // initialize all pointers to 0 (NULL)
return 0;
}
Sample result:
Enter a sentence with at most 10 words and 100 characters:
C++ programming with pointer is very interesting
0: C++
1: programming
2: with
3: pointer
4: is
5: very
6: interesting