Wednesday, July 6, 2011

First Pointers

Below is the code we did in class on pointers. It includes basic pointers, A dynamic array using a pointer and the keyword "new" and a dynamic structure.


#include <iostream>
#include <string>

using namespace std;

//function proto types
void SimplePointer();
void DynamicArrays();
void DynamicStructure();

struct menu
{
string item;
double price;
};

int main()
{
//SimplePointer();
//DynamicArrays();
DynamicStructure();
char c;
cin >> c;
}

void SimplePointer()
{
int number=456;
int * p_number; // pointer
p_number= &number; //assigning the address of a variable to the pointer
int *p_number2; //a second pointer
p_number2=p_number; //assigning the address of one pointer to another


cout << " the number is " << number << " the address of the number is " << p_number
<< " the value stored at that address is " << *p_number
<< "the second pointer has an address of " << p_number2 << "and has an value of "
<< *p_number2 << endl;
}

void DynamicArrays()
{
cout << "Enter the size of the array you want " <<endl;
int size;
cin >> size;

//if you use a pointer you can assign the size
//of an array at run time
//otherwise it requires a constant
int *p_array=new int[size];

for (int i =0;i<size;i++)
{
cout << "Enter your value : ";
cin >> p_array[i];
}

cout << "the second element of the array is " << p_array[1] << "| " << p_array <<"| "
<< p_array + 2<< " |"<< *p_array + 2 << endl;

//you should always delete anything
//you allocate with "new"
delete p_array;

}

void DynamicStructure()
{
//a dynamic structure
//this allows you to assign values to the structure
//during run time
menu * p_menu = new menu;
cout << "Enter the menu item name " << endl;
getline(cin, p_menu->item);
cout << "Enter the Price "<< endl;
cin >> p_menu->price;

cout << "You ordered " << p_menu->item << " at " << p_menu ->price << endl;

delete p_menu;
}

No comments:

Post a Comment