Ok I am reading about pointers and understanding what they do and how to use them but not WHY you would use them can anyone give me any examples of where pointers would be used?
Thanks
Ran
Ok I am reading about pointers and understanding what they do and how to use them but not WHY you would use them can anyone give me any examples of where pointers would be used?
Thanks
Ran
The more you use them the more uses you will see for pointers.
To begin with they can be used to pass by reference but their real power comes later when you are dealing with dynamic memory and data structures like linked lists and binary trees.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
Pointers can be confusing, and at times, you may wonder why you would ever want to use them.
#include <iostream.h>
int main()
{
int x; //A normal integer
int *pointer; //A pointer to an integer
pointer=&x; //Read it, "pointer equals the address of x"
cin>>x; //Reads in x
cout<<*pointer; //Note the use of the * to output the actual number stored in x
return 0;
}
Not the easiest example, but definitely one of my favourites . This example uses a pointer to the video-memory so you can "draw things" on screen. Note: you must use a DOS compiler for this code to work.
You could also use pointers to make lots of objects out of a class in a simple way:Code:#include <conio.h> int main() { //make pointer to video memory unsigned char* Vga=(unsigned char*)0xA0000000; //Initialises mode 13 asm mov ax, 0x13; asm int 0x10; //Plots a white pixel at 20, 10 Vga[10*320+20]=15; //Pause getch(); //Return to text mode asm mov ax, 0x03; asm int 0x10; //exit return 0; }
That is a lot easier than doing this:Code:class MYCLASS { ... }; int main() { //Create pointer MYCLASS* Object; //Allocate memory for 1024 objects Object=new MYCLASS[1024]; ... //Remember to remove the allocated memory delete[] Object; return 0; }
Code:int main() { MYCLASS Object1; MYCLASS Object2; MYCLASS Object3; . . . MYCLASS Object1023; MYCLASS Object1024; }
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.
A little footnote:
Be careful when using pointers, especially if you are not so familiar with them. If you don't know where it "points to" and tries to write some data you can do serious damage to your computer...
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.
This is a really nice tutorial
http://pw2.netcom.com/~tjensen/ptr/cpoint.htm