Us C++ 2021 04

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

C++: Pointers & Strings

Presenter: Dr. Ha Viet Uyen Synh.


Pointer
A pointer is a variable that holds the address of something
else.
 “&” operator gets the address of a variable.
 “*” operator gets a value of a pointer

int foo;
int *x;

foo = 123;
x = &foo;
foo = foo + 5;
// *x = *x+5;
Example
Assigning a value to a
dereferenced pointer
A pointer must have a value before you can
dereference it (follow the pointer).

int *x; int foo;


*x=3; int *x;
x = &foo;
*x=3;
Pointers to anything

x some int
int *x;
int **y; y some *int some int

double *z; z some double


Pointers and Arrays
An array name is basically a const pointer.
You can use the [] operator with a pointer:

int *x;
int a[10]; x is “the address of a[2] ”
x = &a[2];
for (int i=0;i<3;i++)
x[i]= x[i]+1;
x[i] is the same as a[i+2]
Pointer arithmetic
Integer math operations can be used with pointers.
If you increment a pointer, it will be increased by the
size of whatever it points to.

int *ptr = a;
*(ptr+2)
*(ptr+4)
*ptr

a[0] a[1] a[2] a[3] a[4]


int a[5];
Printing an array

void print_array(int a[], int len) {


for (int i=0;i<len;i++)
cout << "[" << i << "] = "
<< a[i] << endl;
}

void print_array(int *a, int len) {


for (int i=0;i<len;i++)
cout << "[" << i << "] = "
<< *a++ << endl;
}
String
A string is a null terminated array of characters.
null terminated means there is a character at the end of
the the array that has the value 0 (null).
Pointers are often used with strings:
char *msg = “RPI”;
char msg2[] = “RPI”;
char msg3[] =
{‘R’,’P’,’I’,0};

msg

'R' 'P' 'I' 0


Arrays of Pointers
const char * const suit[ 4 ] = { "Hearts", "Diamonds", "Clubs",
"Spades" };
Function
Readability: sqrt(5) is clearer than copy-pasting in an
algorithm to compute the square root

Maintainability: To change the algorithm, just change


the function (vs changing it everywhere you ever used
it)

Code reuse: Lets other people use algorithms you’ve


implemented

Function declarations need to occur before


invocations
Syntax

int add2ints(int a, int b) {


return(a+b);
}
Function parameters
The parameters are local variables inside the body of
the function.
When the function is called they will have the values
passed in.
The function gets a copy of the values passed in (we
will later see how to pass a reference to a variable).
Example
int add2nums( int int main(void) {
firstnum, int secondnum ) int y,a,b;
{
int sum; cout << "Enter 2
numbers\n";
cin >> a >> b;
sum = firstnum +
secondnum; y = add2nums(a,b);

// just to make a point cout << "a is " << a <<


firstnum = 0; endl;
secondnum = 0; cout << "b is " << b <<
endl;
return(sum); cout << "y is " << y <<
endl;
}
return(0);
}
Local & Global variables
Parameters and variables declared inside the
definition of a function are local.
They only exist inside the function body.
Once the function returns, the variables no longer
exist!

You can declare variables outside of any function


definition – these variables are global variables.
Any function can access/change global variables.
References
A reference variable is an alternative name for a
variable.
A reference variable must be initialized to reference
another variable.
Once the reference is initialized you can treat it just like
any other variable.
To declare a reference variable you precede the variable
name with a “&”:
int &foo;
char &c;

int count;
int &blah = count;
Example
void add10( int &x) {
x = x+10;
}

add10(counter);

void swap( int &x, int &y) {


int tmp;
tmp = x;
x = y;
y = tmp;
}
Any question?
Exercise 1
Write a function that prints a triangle

triangle(4); triangle(5);

* *
*** ***
***** *****
******* *******
*********
Exercise 2
Write a strcpy function that copys a
string to another one.
Write a strcmp function that compares 2 strings and
returns true if they are the same string, false if they
are not.
Write a strspc function that removes all spaces from a
string.
Exercise 3
(Square of Asterisks) Write a function that displays at
the left margin of the screen a solid square of asterisks
whose side is specified in integer parameter side. For
example, if side is 4, the function displays the following:

* * * *
* * * *
* * * *
* * * *

(Square of Any Character) Modify the function created to


form the square out of whatever character inputted from
keyboard.
Exercise 4
Write a program that inputs three double-precision,
floating-point numbers and passes them to a function
that returns the smallest number.
Exercise 5
(Perfect Numbers) An integer is said to be a perfect
number if the sum of its divisors, including 1 (but not
the number itself), is equal to the number. For
example, 6 is a perfect number, because 6 = 1 + 2 +
3. Write a function isPerfect that determines whether
parameter number is a perfect number. Use this
function in a program that determines and prints all
the perfect numbers between 1 and 1000. Print the
divisors of each perfect number to confirm that the
number is indeed
Exercise 6
Write a function that prints a character 8

char8(5);

* * * * *
* *
* * * * *
* *
* * * * *
Exercise 7
Write a function that prints a solid inverse triangle
solinvtriangle(4);
*******
*****
***
*
Write a function that prints an inverse triangle
invtriangle(4);
*******
* *
* *
*
Exercise 8
Write a program to pass in a integer number. Output
2 numbers: one number includes the odd position
number characters, another includes the even
position number characters. Calculate the total of the
two numbers.
Ex:
Input: 245387
Output: 258 and 437
Total: 695
Any Questions?

[email protected]
Quiz #4
(Prime Numbers) An integer is said to be prime if it’s
divisible by only 1 and itself. For example, 2, 3, 5 and 7
are prime, but 4, 6, 8 and 9 are not.
a) Write a function that determines whether a number is
prime.
b) Use this function in a program that determines and
prints all the prime numbers between 2 and 10,000.
How many of these numbers do you really have to test
before being sure that you’ve found all the primes?
c) Initially, you might think that n/2 is the upper limit for
which you must test to see whether a number is prime,
but you need only go as high as the square root of n.
Why? Rewrite the program, and run it both ways.
Estimate the performance improvement.

You might also like