Slide 7-C++ Pointers
Slide 7-C++ Pointers
#include <iostream.h>
void main(void)
{
int x = 25;
cout << "The address of x is " << &x << endl;
cout << "The size of x is " << sizeof(x) << " bytes\n";
cout << "The value in x is " << x << endl;
}
void main(void)
{
int x = 25;
int *ptr;
x
25
ptr
0x7e00
Address of x: 0x7e00
void main(void)
{
int x = 25;
int *ptr;
void main(void)
{
int x = 25, y = 50, z = 75;
int *ptr;
cout << "Here are the values of x, y, and z:\n";
cout << x << " " << y << " " << z << endl;
ptr = &x; // Store the address of x in ptr
*ptr *= 2; // Multiply value in x by 2
ptr = &y; // Store the address of y in ptr
*ptr *= 2; // Multiply value in y by 2
ptr = &z; // Store the address of z in ptr
*ptr *= 2; // Multiply value in z by 2
cout << "Once again, here are the values of x, y, and z:\n";
cout << x << " " << y << " " << z << endl;
}
#include <iostream.h>
void main(void)
{
short numbers[] = {10, 20, 30, 40, 50};
numbers
void main(void)
{
int numbers[5];
#include <iostream.h>
void main(void)
{
float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0};
float *floatPtr; // Pointer to a float
int count; // array index
#include <iostream.h>
#include <iomanip.h>
void main(void)
{
float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0};
float *floatPtr; // Pointer to a float
int count; // array index
cout.precision(2);
cout << "Here are the values in the coins array:\n";
void main(void)
{
int set[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int *nums, index;
nums = set;
cout << "The numbers in set are:\n";
for (index = 0; index < 8; index++)
{
cout << *nums << " ";
nums++;
}
(Addresses)
void main(void)
{
int set[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int *nums = set; // Make nums point to set
// Function prototypes
void getNumber(int *);
void doubleValue(int *);
void main(void)
{
int number;
getNumber(&number) // Pass address of number to getNumber
doubleValue(&number); // and doubleValue.
cout << "That value doubled is " << number << endl;
}
// Function prototypes
void getSales(float *);
float totalSales(float *);
void main(void)
{
float sales[4];
getSales(sales);
cout.precision(2);
#include <iostream.h>
#include <iomanip.h>
void main(void)
{
float *sales, total = 0, average;
int numDays;
cout << "How many days of sales figures do you wish ";
cout << "to process? ";
cin >> numDays;
sales = new float[numDays]; // Allocate memory