GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rating: Thread Rating: 5 votes, 5.00 average.
  #21  
Old 20-Jun-2004, 19:43
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XIII.Some Things You Ought To Know II :: Switch, Time, Functs


XIII.a)Switch
I'm sure EP4 seems tremendously pathetic and is totally out of place with the compact, efficent world of C++, well, using "switch” can easily simplify things.
CPP / C++ / C Code:
Syntax:
switch( variable)
	{
	case X1: do1();
		   break;
	case X2: do2();
		   break;
	.
	.
	.
	default: don(); 	
	}
This is the equivalent of:
CPP / C++ / C Code:
 
if(variable==X1) do1();
else if(variable==X2) do2();
else ......
else don();

break; is used to exit switch. If break isn’t there, the compiler will go on executing the code until it encounters a break statement.

default accounts for any possibility not listed in case.

doX(); can be any piece of code.

XIII.b)Useful Functions
These functions are called library functions. They are functions defined in files called library file ( files containing machine-executable code accessed by the compiler - one of the things I was referring to in II.b).

i)getch()
Pauses until the user hits a key. The character is returned. getch() doesn't show the the character, getche() does.
ii)clrscr()
Clears the screen, equivalent to cls in DOS
iii)sizeof(data type)
Returns the amount of memory reserved for the data type.
CPP / C++ / C Code:
Example: cout<<sizeof(int) // 2 bytes
 cout<<sizeof(char)// 1 byte
 Example: struct student
	{
             int rollno;
	char name[30];
	float percentage;
	};	
	cout<<sizeof(student)  // 36 bytes
Remember, when you declare a structure, you are creating your own data type like int, char or float. As student contains 1 integer (2 bytes), 30 characters (30*1 bytes) and 1 float(4 bytes) it comes upto 36 bytes.

Similarly, sizeof can be used for arrays.
Example: char name[30];
cout<<sizeof(name); //Output:30

iv)kbhit()
Very useful function. Doesn't hold up the programme like getch() but waits for a key to be pressed. If a key is pressed the function returns TRUE. The character can be retrieved with getch();
v)exit(int arg)
Exits the programme. Arg=0, implies a normal exit, whereas a non-zero value means there was some error. Useful in understanding code.
vi)delay(int), sleep(int)
Pauses the programme for the no.of seconds(for sleep) or milliseconds(for delay) specified in the argument.
Please note:
CPP / C++ / C Code:
getch();   -|	
clrscr();	   |-><conio.h>
kbhit();    -|

exit();	-<process.h>

delay();	|_<dos.h>
sleep();	|

III.c)TIME_T
The time_t data type is used...you can guess..to store time. The function clock() returns
the number of CLOCK TICKS taken place from the beginning of the programme. My compiler says that 18.2 clock ticks takes place per second. The data type time_t stores time in clock ticks, so to convert it into seconds, you have to divide it by 18.2 or CLK_TCK, the constant which comes in the header file <time.h> and holds the number of clock ticks per second.
CPP / C++ / C Code:
Example:
#include <time.h>
void main()
{
int no;
time_t start,end;

cout<<"\nType 123456789: ";
start=clock();
cin>>no;
end=clock();
cout<<"\nTime taken to type 123456789: "<< (end-start)/CLK_TCK;
}
  #22  
Old 20-Jun-2004, 19:44
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XIII.Some Things You Ought To Know :: Infinite Loops, int main()


XIII.d)Infinite Loops
When do you think this loop will end?
CPP / C++ / C Code:
for(;;)
	{
	cout<<"\nC++ Basics by Mithun Jacob a.k.a Phantom XXIII";
	}

Never. It's an infinite loop...as there are no conditions for it to break, it will go on for ever....well as long as the programme can be run... Hit Ctrl+Break or Ctrl+C to get out of such a loop. This may seem useless but in certain cases, all the conditions you need won't fit in the for loop's arguments, example:
CPP / C++ / C Code:
for(;;)
	{
	cout<<"\nEnter age: ";
	cin>>age;
	if(age<18) break;
	cout<<"\nEnter favourite number: ";
	cin>>num;
	if(num!=5) break;
	}

Of course, an alternative is:
CPP / C++ / C Code:
for(; age>=18 && num==5 ;)
	{
	cout<<"\nEnter age: ";
	cin>>age;
	cout<<"\nEnter favourite number: ";
	cin>>num;
	}

But if you don't want the "Enter favourite number" question to appear if the age<18, a possible solution is with the infinite loop.

Similarly:
CPP / C++ / C Code:
while(1)
	{
	--code--
	}
Or:
do
	{
	--code--
	}while(1);

XIII.e)Use of int main()
A good question: What's the use of the int in int main()? I mean, we aren't returning anything are we?

Well, the return statement in a function ENDS the function.

eg.
CPP / C++ / C Code:
int test(char ch)
	{
	if(ch=='F') return 0;
	cout<<"\nYou have passed the test!";
	return 1;	
	}

I could have done this with an else statement, but if ch=='F', the function will end due to the return statement.

So, as main is also a function, return can be used to prematurely end the programme.
CPP / C++ / C Code:
int main()
{
int a,b;
cout<<"\nEnter nos. to be divided: ";
cin>>a>>b;
if (b==0) return 0;
cout<<a/b;
}
  #23  
Old 20-Jun-2004, 19:45
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XIII.Some Things You Ought To Know About :: ASCII Vals, ?:


XIII.f)Some Important ASCII values
ASCII values and their corresponding characters have been very useful to me while programming with an old compiler like Turbo C++ 3.0 (available on my site) so here's a few:

'\r' : 13 : Return
'\n' : 10 : Newline
'\a' : 7 : Beep
'\t' : 9 : Tab
backspace : 8
Esc : 27
'0' : 48
'A' : 65
'a' : 97

Btw, ASCII characters can be displayed using their ASCII values in DOS..just type ALT+X where X is the ASCII value of the character.

Suppose you wanted to enter a slash into your cout statement....try it and you'd be surprised..the reason why you don't see the slash is the '\' is used to tell the compiler that coupled with the next character, they represent something special..like '\n' or '\r'. So to get '\' we throw in another, or '\\'.

Btw, these are called escape sequences. The reason why it's called an escape sequence, is because it adds more meaning to the letter used, or it's an "escape" from the normal use of the
respective letter.

Another useful escape sequence is '\xDD', using this we can output hexadecimal values.
Eg.
cout<<'\x41'; //41 is the hexadecimal equivalent of 'A'


XIII.g)The Conditional Operator
Here's another way to compact a (sometimes) unneccesarily large if-else situation.

Consider this:
if( a>b) c=a
else c=b;


This can be compacted to one line:

c= (a>b)? a:b;

Which means, if (a>b) go for the first one, i.e. a else if the condition is false, go for the second choice, b.
  #24  
Old 20-Jun-2004, 19:47
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

Example Programme #5


EP5:
->Make a progarmme which calculates the typing speed of the user in words per minute.
CPP / C++ / C Code:
//Example Programme 5: Typing Speed Measurer
#include <iostream.h>
#include <time.h>
#include <conio.h>

#define BACKSPACE 8   
#define LEN 215
#define WORDS 39

int backspace=0,spellerr=0,ptr=-1;

char string[LEN]="The software for the ARPA Network exists partly in the IMPs and partly in the respective HOSTs.  BB&N has specified the software of the IMPs and it is the responsibility of the HOST groups to agree on HOST software.";

char typo[LEN];

void menu();
int analyse(char);
void checkSpell();

void main()
{
clrscr();
char ch;
clock_t start,end;

menu();
do
	{
	ch=getch();
	if(ptr==0) start=clock();
	}while(analyse(ch));
end=clock();
checkSpell();

cout<<"\n\n=>You typed: \n";
for(int i=0;i<LEN;++i) cout<<typo[i];

cout<<"\n\n=>Your text contained:\n=>"<<spellerr<<" spelling errors\n=>"<<backspace<<" backspaces.";

cout<<"\n\nType Speed: \n"<<WORDS / ( ((end-start)/CLK_TCK)/60 )<<" wpm";

cout<<"\nPress any key to exit....";
getch();
clrscr();
}


void menu()
{
for(int i=0;i<LEN;++i) typo[i]=0;
cout<<"\n=======>Type Speed Calculator<========";
cout<<"\n=>1.The number of backspaces typed will be recorded";
cout<<"\n=>2.Spelling errors are counted as the number of deviations";
cout<<"\n\nPlease type out the following passage: \n\n\n";
cout<<string<<"\n\nYour text: \n";
}

int analyse(char ch)
{
switch(ch)
{
case BACKSPACE: ++backspace;
		typo[ptr--]=0;
		cout<<ch<<" "<<ch;
		return 1;		//There's no need for break, as return ends the function
case '\r':	return 0;		//'\r' implies the return key, hence typing's over
default:        typo[++ptr]=ch;
		cout<<ch;
		return 1;
}

}

void checkSpell()
{
for(int i=0;i<LEN;++i) if(typo[i]!=string[i]) ++spellerr;
}

//Btw, string is the first para of RFC 0001
  #25  
Old 20-Jun-2004, 19:48
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XIV.Classes :: Concepts & Defining them


XIV.a)Some Concepts
The most important data structure. A struct containes variables of different types; an array of the same type; but..a class can contain ANYTHING, an array, structure, functions absolutely ANYTHING.

Suppose I wish to manufacture a car...assume I'm the manager of building section. I know that workers A,B & C will "take care" of the motor installation section. I know that workers D,E & F will "take care" of the steering and brake installation. I know that they will DO these things but I really don't know HOW they do it....but the point is, I don't NEED to know how they do it. It's not neccesary for me to have the knowledge of each individual task force assigned to the car.

Now let's take a proper example...functions..in the previous programme, a programmer could blindly use each function without even knowing HOW they work. He might not have a clue as to what cout is but he knows that the function menu() will display it. This is data abstraction..hiding data.

Another important feature is data encapsulation..using classes we can combine or "encapsulate" all the essential features requires into one compact package.

XIV.b)Defining a class
A class can be broadly divided into 3 sections: public, private and protected.

Remember data abstraction? Well, these 3 zones make it happen. IF you declare a function, structure, variables {these entities inside a class are called member functions, etc.} inside the Public zone then these members can be accessed directly.

Maybe you didn't understand that, so I'm going to define a class in the public zone.
[c]class (name)
{
zone1:
<-Members->
zone2:
<-Members->
zone3:
<-Members->
};[/u]
Looks a lot like a structure right? A class is basically a structure with functions...in fact C++ was actually going to be called C with Classes. Anyway, forget the trivia, here's an example:
CPP / C++ / C Code:
#include <iostream.h>
class student
{
private:
float percent;
public:
float marks[5];


void CalcPer()
{
percent=0;
for(int i=0;i<5;++i) percent+=marks[i];
percent/=5;
}
	
void display()
{
for(int i=0;i<5;++i) cout<<"\nSubject "<<i+1<<": "<<marks[i];
cout<<"\nPercentage: "<<percent<<"%";
}
	
void input()
{
for(int i=0;i<5;++i)
	{
	cout<<"\nSubject "<<i+1<<": ";
	cin>>marks[i];
	}
}
};

void main()
{
student Phantom;
Phantom.input();
Phantom.CalcPer();
Phantom.display();
//cout<<Phantom.percent; 		This is incorrect
}
In this example, CalcPer(), display(), and input() are public member functions. What differentiates a public member from a private one (like percent) is it's accessibility outside the class. A member function can access ANYTHING INSIDE THE CLASS, be it a struct, variable, function, whatever. BUT, outside the class you can ONLY access the public variables. That's why cout<<Phantom.percent is incorrect.

As you can see calling and declaration is just like a structure's. We create an object (Phantom) using the class name (student)and access it's members with the '.' operator.

The great thing about an object is that each one is a self-contained entity with it's own data untouched by other objects. Memory locations are created for each variable in the object..but for the member functions, only one memory block is assigned, which is accessed by all objects of the same class.
  #26  
Old 20-Jun-2004, 19:49
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XIV.Classes :: Con&Des, Visibility, Cout&Cin


XIV.c)Hail the Constructor! Down with the Destructor!
Here's the CalcPer() function again:
CPP / C++ / C Code:
void CalcPer()
{
percent=0;
for(int i=0;i<5;++i) percent+=marks[i];
percent/=5;
}
Here's where the constructor is used. The constructor can be used to perform operations which take place simultaneously with the creation of the object. For instance, if you had omitted, percent=0, percent would have a junk value as we were adding to itself and it wasn't initialized with anything in the first place.

Another use of the constructor is to pass values into the class. Suppose I didn't want to use a function to input the marks, and I wanted to enter them when I create the object..another use of the constructor.

And the destructor....sounds ominous, but that's what it really does...destroys the object from the face of the...memory bank. There is a default destructor with each object which releases the memory allocated to it by the compiler...but we can also add to the destructor. The usefulness of the destructor will be shown in Pointers.

A class can only have one destructor but many constructors; this will be explained in Overload. The constructor and destructor functions have the same name as the class but we add a '~' before the destructor. Constructors & destructors return nothing...not even void.

Alright, here's the modified programme where the data is taken in with a constructor & displayed with a destructor.
CPP / C++ / C Code:
class student
{
private:
float percent;
float marks[5];

public:
student(float m[5])								//Constructor
{
percent=0;
for(int i=0;i<5;++i) marks[i]=m[i];	
}

void CalcPer()
{
percent=0;
for(int i=0;i<5;++i) percent+=marks[i];
percent/=5;
}
	
~student()										//Destructor
{
for(int i=0;i<5;++i) cout<<"\nSubject "<<i+1<<": "<<marks[i];
cout<<"\nPercentage: "<<percent<<"%";
}

};

void main()
{
float marks[5]={100,100,90,90,10};

student Phantom(marks);
Phantom.CalcPer();
}
I hope you have understood the significance of a class. Just like a structure, this class in now a data type, like int, float, etc. Therefore it can be passed in functions as an argument, or returned, or basically anything...

Here's a much better way to initialize variables:
CPP / C++ / C Code:
someClass()
	{
	a=1,b=2,c=3;
	cout<<"\nDONE!";
	}

This can be simplified to:

someClass() : a(1),b(2),c(3)
	{
	cout<<"\nDONE!";
	}

Btw, even if you don't have a constructor, there's an automatic built-in constructor known as a default construcor which will create your object.

XIV.d)Visibility
Visibility of an object (an object in the common sense) refers to the locations in a programme it can access.

XIV.e)The Truth Behind cout & cin
So far, we've been blindly using cout & cin...but what are they? Well, they're nothing more than objects of 2 classes, respectively ostream & istream each of them defined in IOSTREAM.H.
__________________
[b]There are times when the Phantom walks the streets as an ordinary man...this is one of those times.
  #27  
Old 20-Jun-2004, 19:50
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XV.Overload :: Functions & Operators


Generally, there would've been an EP after such an important concept...but I've always felt that without overloading, a class isn't really complete..for C++ is really made up of functions and classes, and for YOUR class to be compatible with classes like cout & cin, you must learn to overload operators. But first, functions:

XV.a)Overloading Functions
What is the use of overloading? It gives the programme flexibility. You see, REAL programmers create easy to handle packages used by normal users, like cout for example. And to increase the ease, we have features like classes, functions, etc. Now, consider the following:
CPP / C++ / C Code:
float cuboid_volume(int len, int bre, int hei)	//I've used float again for greater size 
	{
	return len*bre*hei;
	}

	}
float cylinder_volume(int len, int rad)
	{
	return (3.14)*r*r*h;
	}

float sphere_volume(int rad)
	{
	return (4/3)*(3.14)*r*r;
	}

Now, I can use these functions to calculate the volumes of the specified 3 objects. But look at how cumbersome it is! For the same concept, i.e. volume, we have 3 different functions! And in this case there's a difference in each volume...for the cuboid we need 3 dimenrsions, the sphere, 1 and the cylinder, 2. So, wouldn't it be more convenient if we had a function with the same name?
CPP / C++ / C Code:
float volume(int len, int bre, int hei)
	{
	return len*bre*hei;
	}

float volume(int len, int rad)
	{
	return (3.14)*r*r*h;
	}

float volume(int rad)
	{
	return (4/3)*(3.14)*r*r;
	}
See? From now on all you have to do is use volume(..) and the arguments. This is function overloading; you give a function more powers or you "overload" it.

A good question would be: Suppose overloaded a function with the same number of argument? Then it won't work...the compiler will say that the 2 functions are ambigous.

Now, a constructor is a special type of function..which qualifies it for overloading. Therefore, you can overload the constructor to make your class more flexible.

XV.b)Overloading Operators
Alright! The real stuff! Let's make a silly class:
CPP / C++ / C Code:
class  student
{
public:
int roll;
float percent;


/*Suppose you wanted to display the contents of the structure...the "obvious" way would be to make a function...say, display.*/

void display()
	{
	cout<<"\nRoll: "<<roll<<"\nPercent: "<<percent;
	}
};

So to display and assuming the object's name is Phantom...nah, let's name the object Kit, to display the contents: Kit.display();

Now, wouldn't it be infinitely easier if we could use cout? Wouldn't cout<<Kit, be much cooler? Well, if you think about it, cout was created to handle known data types like char, int or float...so what you have to do to make it display the contents of your object is....OVERLOAD IT! So, how do I overload an operator? Simple.
(return type) operator (operator to be overloaded-symbol) (arguments)
{
--code--
}


So can you guess the operator we have to overload? It's '<<'.
CPP / C++ / C Code:
void operator << (ostream &xout, student S)
	{
	xout<<"\nRoll: "<<roll<<"\nPercent: "<<percent;
	}

As you can see, cout is nothing but an object of ostream. Under the ostream class we have various classes, like iostream and (coming up) fstream {used for file handling}.

Another confusing concept might be the order of the arguments, these are important as they determine the way we can use the operator. The first argument comes before the operator and the next one after the operator (in this example with a binary operator like <<).

Please note that all operators can't be overloaded.

And yet, another confusing concept might be the & before, xout. This will be explained in XVII (Pointers).
__________________
[b]There are times when the Phantom walks the streets as an ordinary man...this is one of those times.
  #28  
Old 20-Jun-2004, 19:52
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XV.File Handling


Now, to access a file we use the class "fstream" is FSTREAM.H. Note that cout & cin are already declared in IOSTREAM.H as we're performing the I/O operations on stanard output and input devices like a monitor or a keyboard. But for fstream, we're working with a file..so we have to declare separate objects for each file.

XV.a)Declaring the object, Opening & Closing a file
Declaring:
fstream (name of object);

Example: fstream fil;
Opening:
fil.open( (name of file) , (parameters) );

Now, the parameters are as follows:

ios::in | the file can be read
ios:ut | the file can be written to; note, this will create a new one
ios::binary | will be able to process binary characters
ios::append | Instead of overwriting, it starts at the end of the file

The above are one-bit flags which determines which operation to carry out. You'll see more ios flags in Manipulators (XIX.a).

If you want to have a file with more than one parameter (eg.reading & writing is possible) you should use '|'.

Example: fil.open("names.txt", ios::in|ios:ut|ios::binary);

Closing:
Simple enough.
Example: fil.close();

XV.b)Writing & Reading
The simplest way of reading and writing to a file is by using the get() and put() functions.
To simplify data insertion and extraction, reading and writing is done with the help of a file pointer which "points" to the current byte the object is reading/writing.

Suppose, I read a byte from a file using fil.get(), then the pointer automatically shifts to the next byte. Similarly, suppose I was writing a file, then the byte will be written to the file, and the pointer automatically moves to the next byte, so that the next character written will be after the previous.

CPP / C++ / C Code:
Syntax:
-------
fil.put('A');	//Writes character 'A' to the fil object
ch=fil.get();	//Retrieves character from fil and stores it in ch
fil.get(ch);	//Ditto

The byte number the pointer is on is returned by tellg(), and to set the pointer we use seekg(): both member functions of the fstream class.

CPP / C++ / C Code:
Syntax:
-------
fil.seekg(12);
cout<<fil.tellg();
  #29  
Old 20-Jun-2004, 19:53
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

Example Programme #6


EP6
->Make a programme to copy a file
CPP / C++ / C Code:
//Example Programme 6:Copy
#include <fstream.h>			//Btw, IOSTREAM is inside, FSTREAM so to use cout & cin 						//FSTREAM will do

void main()
{
fstream SRC,DEST;

char *src="z:\\source.txt";             //The source file
char *dest="z:\\destiny.txt";           //The destination file
char ch;

SRC.open(src,ios::in|ios::binary);
DEST.open(dest,ios::out|ios::binary);

while(!SRC.eof())                       //The eof() or END OF FILE function
        {                               //returns true if the end of the
                ch=SRC.get();           //file has been reached
                DEST.put(ch);
        }

DEST.close();
SRC.close();
}
  #30  
Old 20-Jun-2004, 19:54
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XVII.Pointers :: Variables & Arrays


As I've said before, what the programmer actually has at his disposal is a vast array or boxes or memory locations. Now, obviously each box must have an address? Or how else can we efficiently locate it? Therefore, a memory location has 2 aspects to it; it's address and the value it contains.

Now, we've already seen a way to create memory locations with only the value stored in them as the primary aspect, i.e. ordinary (automatic) variables. Now we're going to see another type of variable, a pointer variable which concerns itself with the address of the memory location

XVII.a)Variables
A pointer variable is declared like this:

Syntax:
-------
(data type)* (name);
Eg.char *name;

Hmmm...looks familiar? Like a string perhaps..? Yep, that's what a string is..a pointer variable. Remember when I said all we had in a string was the addres of the memory block storing the first character (IX.Arrays)? Well, that address is stored in the pointer. Actually, for any array..alright, that's the next topic.

So, how about an integer pointer? Why not?

int *num;
cout<<num;

Output: Some hexadecimal number


Why? Because, num stores an address and if we want to see what it contains, we'll see the address it "points" to. Suppose, I wanted to access the value stored in the box or memory block. I should use, *

CPP / C++ / C Code:
int *num;
*num=5;
cout<<"\nAddress: "<<num;
cout<<"\nValue:   "<<*num;

Now how do I link non-pointer variables with normal variables? With the previous definition ANY variable must have a memory block where the value is stored in, therefore, that block must have an address. So, if we could access the address and make a pointer with the same address, we can actually link both variables in a fantastic way.
int num=5;
int *ptr=&num; //Use * to bring out the value of a pointer and use & to bring the address of //an automatic variable


Here, I use & to bring out the address of a normal or automatic variable. Now, guess the output of the following bit of code:
int num=5;
int *ptr=&num;
(*ptr)++;
cout<<num;


If you guessed 5...sorry, as 6 is the right answer. Why? Because, ptr now points to the memory location of num, so any modification done to the memory location ptr points to actually modifies num!

Now, if you remember the data type void, you can apply the same concept here. The benefit of a void pointer is you can use it to point to any sort of value. Let me explain:

If you've noticed, the addresses we assign to the pointers are of variables of the same data type. Try this:
int *ptr;
float a;

ptr=&a; //ERROR!


As float & int are 2 different data types.

But the specialty of the void pointer is that, we can use it to point to any data type, hence making it useful in places where we want to make something applicable to all data types.
CPP / C++ / C Code:
int integer;
float floating;

void *ptr;
ptr=&integer;
ptr=&floating;

XVII.b)Arrays
As I said before, an array actually holds the address of the first element of the array. The rest of the elements are consecutively stored.

Suppose:
CPP / C++ / C Code:
char *str="Phantom";
char *ptr=str;
for(int i=0;i<7;++i,++ptr) cout<<*ptr;

Output: Phantom

How? *str refers to the value held in the location pointed to by str, i.e. the first element or P. By incrementing the pointer ptr, I move to the consecutive memory location which stores the second element and then display it.
 
 

Recent GIDBlogProblems with the Navy (Chiefs) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 15:20.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.