A pointer refers to an address that points to another variable.
So say you have an integer x, and another integer y.
int x, y;
You might have a pointer to the "current" integer:
int *current;
Now you could write something like this:
current=%26amp;x; /* make current point to x */
*current=5; // set x to 5
The advantage here is that you can later set current to %26amp;y and then code that used to modify x will now modify y.
This is useful in functions where you want to modify an argument. For example:
void square(int *x)
{
*x=*x * *x;
}
You might call this as:
int z=50;
square(%26amp;z);
/* now z= 50*50 */
Of course your could write square in this case to return the result, but perhaps you are returning some result already and want to return something else. For example, suppose you want to write a function that gets two numbers and returns the largest and the smallest, you might write:
int numsort(int a, int b, int *smallest)
{
if (a%26gt;b) { *smallest=b; return a; }
else { *smallest=a; return b; } /* if equal, doesn't matter */
return 0; // not reached
}
Another important use is when working with arrays. An array name is a pointer to the first element of the array:
int x[50];
You can even have pointers to functions. For example, you might have a table of function pointers to execute different code based on an index.
Now x is the same as %26amp;x[0] and incrementing x will point at subsequent elements.
Finally, dynamic allocation uses pointers. So another way to handle the array above would be:
int *x;
x=malloc(50*sizeof(int)); /* make array of 50 integers */
/* Now x works just like an array */
. . .
free((void *)x);
How to work with c pointers?
You can also have pointers to functions. Take the addresses of various functions and put them in an arrays of function pointers.
This is useful in implementing state machines and executing different functions according to rules built around calculations rather then if..then..else constructs
Reply://Declare a pointer
int *i; // just prefix a normal variable with *
//Once you are done with your pointer just delete it
delete i;
// to access member functions in pointers use "-%26gt;" instead of "."
this-%26gt;setText("hello");
Note: This is c++, c uses the same conventions with the exception of "//" = "/* */"
land survey
Tuesday, July 14, 2009
Help in C pointers?
#include"stdio.h"
#include"conio.h"
void main()
{
void bubblesort(char *R[], int a); //function declaration//
char *restname[20][30]; //Variable in main//
bubblesort(restname[30], 20)//Function bubblesort in main//
void bubblesort(char *R[], int a)//function bubble sort//
{
int i, j;
char *hold;
for(i= 0; i %26lt; a; i++)
{
for(j=0; j%26lt;a-1; j++)
{
if(R[j] %26lt; R[j+1])
{
hold = R[j];
R[j] = R[j+1];
R[j+1] = hold;}
}
}
for(i=0; i%26lt;a; i++)
{
printf("%s", R[i]);
printf("\n");
}
} //end function//
}
}
help with the declaration part
Help in C pointers?
I see several potential problems...
(1) The function declaration for bubblesort goes above the main, not in it.
(2) The function itself appears within the main function. C doesn't allow nested functions.
(3) That function has as its first parameter an array of pointers to char. Fine, we sort arrays of pointers all the time. But then the sort algorithm sorts by the value of the pointer itself, not the value of the char indicated by that pointer. Sorting the pointers in this manner makes little sense.
Reply:first any function declartion and definition should be out of main scope
not inside the main,the only thing inside the main is the fucntion call :)
secondly your array restname is empty ? why ? what are you sorting ?
good luck :)
#include"stdio.h"
#include"conio.h"
void bubblesort(char *R[], int a)//function bubble sort//
{
int i, j;
char *hold;
hold = new char;
for(i= 0; i %26lt; a; i++)
{
for(j=0; j%26lt;a-1; j++)
{
if(R[j] %26lt; R[j+1])
{
hold = R[j];
R[j] = R[j+1];
R[j+1] = hold;}
}
}
for(i=0; i%26lt;a; i++)
{
printf("%s", R[i]);
printf("\n");
}
} //end function//
void main()
{
char *restname[20][30]; //Variable in main//
bubblesort(restname[30], 20);//Function bubblesort in main//
}
#include"conio.h"
void main()
{
void bubblesort(char *R[], int a); //function declaration//
char *restname[20][30]; //Variable in main//
bubblesort(restname[30], 20)//Function bubblesort in main//
void bubblesort(char *R[], int a)//function bubble sort//
{
int i, j;
char *hold;
for(i= 0; i %26lt; a; i++)
{
for(j=0; j%26lt;a-1; j++)
{
if(R[j] %26lt; R[j+1])
{
hold = R[j];
R[j] = R[j+1];
R[j+1] = hold;}
}
}
for(i=0; i%26lt;a; i++)
{
printf("%s", R[i]);
printf("\n");
}
} //end function//
}
}
help with the declaration part
Help in C pointers?
I see several potential problems...
(1) The function declaration for bubblesort goes above the main, not in it.
(2) The function itself appears within the main function. C doesn't allow nested functions.
(3) That function has as its first parameter an array of pointers to char. Fine, we sort arrays of pointers all the time. But then the sort algorithm sorts by the value of the pointer itself, not the value of the char indicated by that pointer. Sorting the pointers in this manner makes little sense.
Reply:first any function declartion and definition should be out of main scope
not inside the main,the only thing inside the main is the fucntion call :)
secondly your array restname is empty ? why ? what are you sorting ?
good luck :)
#include"stdio.h"
#include"conio.h"
void bubblesort(char *R[], int a)//function bubble sort//
{
int i, j;
char *hold;
hold = new char;
for(i= 0; i %26lt; a; i++)
{
for(j=0; j%26lt;a-1; j++)
{
if(R[j] %26lt; R[j+1])
{
hold = R[j];
R[j] = R[j+1];
R[j+1] = hold;}
}
}
for(i=0; i%26lt;a; i++)
{
printf("%s", R[i]);
printf("\n");
}
} //end function//
void main()
{
char *restname[20][30]; //Variable in main//
bubblesort(restname[30], 20);//Function bubblesort in main//
}
C pointers, give practical examples?
Pointer is a variable that contains the address of another variable. (or in other words the address of a memory location). in 16-bit segmented memory model, there are two types of pointers: near pointer, that points in the same memory segment, and far pointer, which can point to beyond the current memory segment. Near pointer is actually a 16-bit integer that addresses a memory location in the segment pointed to by DS register of processor. While far pointer is 32-bit integer which contains both segment and offset address.
in 32-bit flat addressin mode, pointer is always a 32-bit integer.
One important thing to understand is pointer itself does not contain any data (or code sometimes), rather it contains the address of a memory location where data (or code) can be found. Using this technique is called indirect addressing and multiple indirection could be possible.
I give hereunder a code example which uses the pointers. Two operators in C are very important when using pointers. * is called 'value at' and %26amp; is called 'address of'. here's the code in C:
#include %26lt;conio.h%26gt;
#include %26lt;stdio.h%26gt;
void main()
{
int x=100;
int *ax=%26amp;x;
printf("%d, %d", x, *ax); // will print 100, 100
printf("%d",ax); //will print memory address of x
*ax=200; // you are actually changing x with its pointer ax
printf("%d, %d", x, *ax); // will print 200, 200
printf("%d",ax); //will print memory address of x
}
try this code in a 16-bit C version.
hope that answers the question
C pointers, give practical examples?
pointer is a variable it stores the address of another variable.
say for example
you are declaring a variable integer
int i;
i=10;
int occupies 2 bytes in the memory
say for example
memory address will look like this
8000 8001 8002 8003 ......9000
when you store it in the memory it will converted to binary and occupies the 2 bytes
here int i will occupie from 8000 to 8016
int *ptr;
ptr=%26amp;i (address of i)
so now ptr contains the starting address of i ...
here i starting address is 8000. so ptr= 8000
*ptr = value at address ( 10)
%26amp;i = address of i (8000)
%26amp;ptr= address of ptr ( prt is also variable so it will occupy some space in memmory it will return that base address
for better understanding
buy the book named "pointers in c " by yaswant kanithkar
in 32-bit flat addressin mode, pointer is always a 32-bit integer.
One important thing to understand is pointer itself does not contain any data (or code sometimes), rather it contains the address of a memory location where data (or code) can be found. Using this technique is called indirect addressing and multiple indirection could be possible.
I give hereunder a code example which uses the pointers. Two operators in C are very important when using pointers. * is called 'value at' and %26amp; is called 'address of'. here's the code in C:
#include %26lt;conio.h%26gt;
#include %26lt;stdio.h%26gt;
void main()
{
int x=100;
int *ax=%26amp;x;
printf("%d, %d", x, *ax); // will print 100, 100
printf("%d",ax); //will print memory address of x
*ax=200; // you are actually changing x with its pointer ax
printf("%d, %d", x, *ax); // will print 200, 200
printf("%d",ax); //will print memory address of x
}
try this code in a 16-bit C version.
hope that answers the question
C pointers, give practical examples?
pointer is a variable it stores the address of another variable.
say for example
you are declaring a variable integer
int i;
i=10;
int occupies 2 bytes in the memory
say for example
memory address will look like this
8000 8001 8002 8003 ......9000
when you store it in the memory it will converted to binary and occupies the 2 bytes
here int i will occupie from 8000 to 8016
int *ptr;
ptr=%26amp;i (address of i)
so now ptr contains the starting address of i ...
here i starting address is 8000. so ptr= 8000
*ptr = value at address ( 10)
%26amp;i = address of i (8000)
%26amp;ptr= address of ptr ( prt is also variable so it will occupy some space in memmory it will return that base address
for better understanding
buy the book named "pointers in c " by yaswant kanithkar
Sunday, July 12, 2009
C++ Pointers?
Say you know a memory location address (say 0x22ff70) and you want to know what is stored there (if anything), how do you go about printing the contents on screen?
C++ Pointers?
Casting, that is the magic of C++.
Try these articles.
http://www.boost.org/libs/conversion/cas...
http://en.wikipedia.org/wiki/Pointer
http://www.informit.com/guides/content.a...
Good luck
Reply:U can store this address in a pointer. Get the value thro' *
I think its correct. I studied this long back. Sorry if am wrong
Reply:If you want to print the valud of a variable you "Printf("%i",varr). (For example)
If its a pointer you have to "Printff("%i";%26amp;point). You have to tell the printing function to print not the value of the pointer (0x22ff70 in this case) but the value of the address the pointer points :).
Reply:If you know exactly data type kept at this address, do the following:
...
known_data_type * ptr = (known_data_type) void_pointer;
// print your known data here...
...
In another case, you cah just cast this address to char* or unsigned char * and get some dump:
...
unsigned char * up = (unsigned char *) void_pointer;
dump( up, any_size_you_need_if you_know_it);
C++ Pointers?
Casting, that is the magic of C++.
Try these articles.
http://www.boost.org/libs/conversion/cas...
http://en.wikipedia.org/wiki/Pointer
http://www.informit.com/guides/content.a...
Good luck
Reply:U can store this address in a pointer. Get the value thro' *
I think its correct. I studied this long back. Sorry if am wrong
Reply:If you want to print the valud of a variable you "Printf("%i",varr). (For example)
If its a pointer you have to "Printff("%i";%26amp;point). You have to tell the printing function to print not the value of the pointer (0x22ff70 in this case) but the value of the address the pointer points :).
Reply:If you know exactly data type kept at this address, do the following:
...
known_data_type * ptr = (known_data_type) void_pointer;
// print your known data here...
...
In another case, you cah just cast this address to char* or unsigned char * and get some dump:
...
unsigned char * up = (unsigned char *) void_pointer;
dump( up, any_size_you_need_if you_know_it);
C++ pointers question?
I understand points and stuff but where would I use it? they seem useless and seem like something I would never use.
can you give me some examples and maybes some codes to help me understand when I would use them?
Thanks,
S_R_S
C++ pointers question?
Pointer code is more educational than practical. You really need to fully understand the usage of memory and pointers to store values in order to write efficient code and manage memory correctly.
My recollection from school is that most pointer operations were performed in lists, data collections, and sorting methods. These are high level ops that will already be written into the pre-existing utility libraries that you will frequently use. But you really need to understand what is going on under the covers.
Reply:We can define a variable in C++ to store a memory address. A pointer in C++ is said to "point to" the memory address that is stored in it. Also, when defining a C++ pointer variable, we must specify the type of variable to which it is pointing. For example, to define a pointer, which will store a memory address at which exists an int, we can do the following:
int *p,a;
here a is a ordinary variable,p is a pointer variable to store the address of a.
a=5;
p=%26amp;a;
where a contains the value 5 and p contains the address of a(memory address)
here '%26amp;' is a 'reference' or 'address operator'
Reply:Scott, C++ is a language of pointers. It's probably difficult for you to understand this now; however, if you keep at it, you'll eventually see the power of pointers. All the crap you're learning about classes are in fact teaching you about pointers.
Example. We have a class called location. In the location class, we have GPS Latitude and GPS Longitude and other stuff.
class location
{
DOUBLE GPSLat;
DOUBLE GPSLong;
DOUBLE Altitude;
VOID function1(....)
}
From the location class, we'll derive a Ship class and Human class.
class Ship::location
{
DOUBLE heading;
DOUBLE speed;
etc.
}
class Human::location
{
BOOL Man;
DOUBLE Height;
DOUBLE Weight;
etc.
}
From our main program we have five boats (from ship) and four Eskimos
from human.
Ship boat[5];
Human Eskimo[4];
main()
{
......
// somewhere in here we want to print the location data
// of a ship or an Eskimo. It'll be user or programmatically
// selectable
location* myTarget;
myTarget = %26amp;boat[4]; or myTarget = %26amp;Eskimo[0]; or, etc. (SOME INPUT)
printf( "%f, %f", myTarget-%26gt;GPSLat, myTarget-%26gt;GPSLong );
Note how the printf function does NOT need to change. It will
work on all ships or Eskimos and it does not include even an index
into the arrays. You would obviously make a more meaningful
routine than just a printf.
Hope this helps. (C++ in one minute).
Reply:Pointers are not easier to understand but they are much easier to understand if you go back to the C programming language. C was written originally on computers so simple you can buy calculators today which are more complicated and have more memory. For that reason, a lot of under the hood stuff was and is pretty much out in the open. An example of this would be pointers and arrays. Everything in C, we are told, is passed as a value except arrays. These are passed by the address of the first element Array[0]. In practical terms, this means when you pass an array to a function what you have is a pointer to that array, on which you can (though it's not recommended) do pointer arithmatic. You are better off creating a temporary pointer, assigning it Array[0]'s address and using that because it will help you keep track of things. With C++ you can use the %26amp; operator to pass anything by reference, and it is certainly less cumbersome, but the reason C code is supposed to compile into such fast and efficient machine code is it stays close to what the hardware is actually doing and what you are trading off is readability for efficiency. Read Kernighan and Ritchie's The C Programming Language even if you are not particularly interested in programming in C. You'll find source code for many functions in cstdio and cstlib which use pointers, and frankly which if you come to understand (and these guys are good at explaining) will help you understand pointers better than anyone at Yahoo! Answers
survey software
can you give me some examples and maybes some codes to help me understand when I would use them?
Thanks,
S_R_S
C++ pointers question?
Pointer code is more educational than practical. You really need to fully understand the usage of memory and pointers to store values in order to write efficient code and manage memory correctly.
My recollection from school is that most pointer operations were performed in lists, data collections, and sorting methods. These are high level ops that will already be written into the pre-existing utility libraries that you will frequently use. But you really need to understand what is going on under the covers.
Reply:We can define a variable in C++ to store a memory address. A pointer in C++ is said to "point to" the memory address that is stored in it. Also, when defining a C++ pointer variable, we must specify the type of variable to which it is pointing. For example, to define a pointer, which will store a memory address at which exists an int, we can do the following:
int *p,a;
here a is a ordinary variable,p is a pointer variable to store the address of a.
a=5;
p=%26amp;a;
where a contains the value 5 and p contains the address of a(memory address)
here '%26amp;' is a 'reference' or 'address operator'
Reply:Scott, C++ is a language of pointers. It's probably difficult for you to understand this now; however, if you keep at it, you'll eventually see the power of pointers. All the crap you're learning about classes are in fact teaching you about pointers.
Example. We have a class called location. In the location class, we have GPS Latitude and GPS Longitude and other stuff.
class location
{
DOUBLE GPSLat;
DOUBLE GPSLong;
DOUBLE Altitude;
VOID function1(....)
}
From the location class, we'll derive a Ship class and Human class.
class Ship::location
{
DOUBLE heading;
DOUBLE speed;
etc.
}
class Human::location
{
BOOL Man;
DOUBLE Height;
DOUBLE Weight;
etc.
}
From our main program we have five boats (from ship) and four Eskimos
from human.
Ship boat[5];
Human Eskimo[4];
main()
{
......
// somewhere in here we want to print the location data
// of a ship or an Eskimo. It'll be user or programmatically
// selectable
location* myTarget;
myTarget = %26amp;boat[4]; or myTarget = %26amp;Eskimo[0]; or, etc. (SOME INPUT)
printf( "%f, %f", myTarget-%26gt;GPSLat, myTarget-%26gt;GPSLong );
Note how the printf function does NOT need to change. It will
work on all ships or Eskimos and it does not include even an index
into the arrays. You would obviously make a more meaningful
routine than just a printf.
Hope this helps. (C++ in one minute).
Reply:Pointers are not easier to understand but they are much easier to understand if you go back to the C programming language. C was written originally on computers so simple you can buy calculators today which are more complicated and have more memory. For that reason, a lot of under the hood stuff was and is pretty much out in the open. An example of this would be pointers and arrays. Everything in C, we are told, is passed as a value except arrays. These are passed by the address of the first element Array[0]. In practical terms, this means when you pass an array to a function what you have is a pointer to that array, on which you can (though it's not recommended) do pointer arithmatic. You are better off creating a temporary pointer, assigning it Array[0]'s address and using that because it will help you keep track of things. With C++ you can use the %26amp; operator to pass anything by reference, and it is certainly less cumbersome, but the reason C code is supposed to compile into such fast and efficient machine code is it stays close to what the hardware is actually doing and what you are trading off is readability for efficiency. Read Kernighan and Ritchie's The C Programming Language even if you are not particularly interested in programming in C. You'll find source code for many functions in cstdio and cstlib which use pointers, and frankly which if you come to understand (and these guys are good at explaining) will help you understand pointers better than anyone at Yahoo! Answers
survey software
Why do c pointers are faster than variables accessing?
why the accesing time is fast of pointers than that of variables
Why do c pointers are faster than variables accessing?
When accessing a variable there may be a need to compute the address of the variable, while the pointer has that address already computed. For example, if the variable is an element of
an array, accessed as a[b], a computation of the address using
b would be necessary, making it slower.
Why do c pointers are faster than variables accessing?
When accessing a variable there may be a need to compute the address of the variable, while the pointer has that address already computed. For example, if the variable is an element of
an array, accessed as a[b], a computation of the address using
b would be necessary, making it slower.
C++ Pointers; Can someone use illustrations and explain?
Can someone give a simple explanation of the use of Pointers, how they work, and their purpose. Illustrations would be a +.
C++ Pointers; Can someone use illustrations and explain?
What are pointers?
Pointers are aptly named: they "point" to locations in memory. Think of a row of safety deposit boxes—of various sizes—at a local bank. Each safety deposit box will have a number associated with it, so that the teller can quickly look it up. These numbers are like the memory addresses of variables. A pointer in the world of safety deposit boxes would simply be anything that stored the number of another safety deposit box.
Perhaps you have a rich uncle who stored valuables in his safety deposit box, but decided to put the real location in another, smaller, safety deposit box that only stored a card with the number of the large box with the real jewelery. The safety deposit box with the card would be storing the location of another box; it would be equivalent to a pointer. In the computer, pointers are just variables that store memory addresses, usually the addresses of other variables.
The cool thing is that once you can talk about the address of a variable, you'll then be able to go to that address and retrieve the data stored in it. If you happen to have a huge piece of data that you want to pass into a function, it's a lot easier to pass its location to the function than to copy every element of the data! Moreover, if you need more memory for your program, you can request more memory from the system—how do you get "back" that memory? The system tells you where it is located in memory. In other words, you get a memory address back. And you need pointers to store the memory address.
A note about terms: the word pointer can refer either to a memory address itself, or to a variable that stores a memory address. Usually, the distinction isn't really that important: if you pass a pointer variable into a function, you're passing the value stored in the pointer—the memory address. When some people want to talk about a memory address, they refer to it as a memory address. When they want a variable that stores a memory address, they call it a pointer. When a variable stores the address of another variable, they say that it is "pointing to" that variable.
___________
Pointer Syntax
___________
Pointers require a bit of new syntax because when you have a pointer, you need the ability to request both the memory location it stores and the value stored at that memory location. Moreover, since pointers are somewhat special, you need to tell the compiler when you declare your pointer variable that the variable is a pointer, and tell the compiler what type of memory it points to.
The pointer declaration looks like this:
%26lt;variable_type%26gt; *%26lt;name%26gt;;
For example, you could declare a pointer that stores the address of an integer with the following syntax:
int *pointer1; // points to an integer
Notice the use of the *. This is the key to declaring a pointer; if you add it directly before the variable name, it will declare the variable to be a pointer.
Important: if you declare multiple pointers on the same line, you must precede each of them with an asterisk:
// one pointer, one regular int
int *pointer1, non_pointer1;
// two pointers
int *pointer1, *pointer2;
As I mentioned, there are two ways to use the pointer to access information: it is possible to have it give the actual address to another variable. To do so, simply use the name of the pointer without the *. However, to access the actual memory location, use the *. The technical name for this doing this is 'dereferencing the pointer.' Basically, you're taking the reference to some memory address and following it, to retrieve the actual value. It can be tricky to keep track of when you should add the asterisk. Remember that the pointer's natural use is to store a memory address; so when you use the pointer, i.e., pointer1, then, it evaluates to the address. You have to add something extra—the asterisk (*pointer1)—in order to retrieve the value stored at the address. You'll probably do that an awful lot. Nevertheless, the pointer itself is supposed to store an address, so when you use the bare pointer, you get that address back.
Pointing to Something: Retrieving an Address
In order to have a pointer actually point to another variable it is necessary to have the memory address of that variable also. To get the memory address of a variable (its location in memory), put the %26amp; sign in front of the variable name. This makes it give its address. This is called the address-of operator, because it returns the memory address.
Conveniently, both ampersand and address-of start with 'a;' that's a useful way to remember that you use %26amp; to get the address of a variable.
For example:
#include %26lt;iostream%26gt;
using namespace std;
int main()
{
int x; // A normal integer
int *p; // A pointer to an integer
p = %26amp;x; // Read it, "assign the address of x to p"
cin%26gt;%26gt; x; // Put a value in x, we could also use *p here
cin.ignore();
cout%26lt;%26lt; *p %26lt;%26lt;"\n"; // Note the use of the * to get the value
cin.get();
}
The cout outputs the value stored in x. Why is that? Well, let's look at the code. The integer is called x. A pointer to an integer is then defined as p. Then it stores the memory location of x in pointer by using the address-of operator (%26amp;) to get the address of the variable. Using the ampersand is a bit like looking at the label on the safety deposit box to see its number rather than looking inside the box, to get what it stores. The user then inputs a number that is stored in the variable x; remember, this is the same location that is pointed to by p.
The next line then passes *p into cout. *p performs the "dereferencing" operation on p; it looks at the address stored in p, and goes to that address and returns the value. This is similar to looking inside a safety deposit box only to find the number of (and, presumably, the key to ) another box, which you then open.
Notice that in the above example, pointer is initialized to point to a specific memory address—before it is used. If this was not the case, it could be pointing to anything. This can lead to extremely unpleasant consequences to the program. For instance, the operating system will probably prevent you from accessing memory that it knows your program doesn't own: or else, your program would crash. If it let you use unowned memory, you could mess with the memory of any running program. For example, if you had a document opened in Word, you could change the text! Fortunately, Windows and other modern operating systems will stop you from accessing that memory—by causing your program to crash. To avoid crashing your program, you should always initialize pointers before you use them.
[Side note: It is also possible to initialize pointers using free memory. This allows dynamic allocation of array memory. It is most useful for setting up structures called linked lists.]
The keyword 'new' is used to initialize pointers with memory from free store (a section of memory available to all programs). The syntax looks like the example:
int *ptr = new int;
It initializes ptr to point to a memory address of size int (because variables have different sizes, number of bytes, this is necessary). The memory that is pointed to becomes unavailable to other programs. This means that the careful coder should free this memory at the end of its usage.
The delete operator frees up the memory allocated through new. To do so, the syntax is as in the example:
delete ptr;
After deleting a pointer, it is a good idea to reset it to point to 0. When 0 is assigned to a pointer, the pointer becomes a null pointer, in other words, it points to nothing. By doing this, when you do something foolish with the pointer, you find out immediately—instead of later, when you have done considerable damage.
In fact, the concept of the null pointer is frequently used as a way of indicating a problem—for instance, some functions left over from C return 0 if they cannot correctly allocate memory (notably, the malloc function).
C++ Pointers; Can someone use illustrations and explain?
What are pointers?
Pointers are aptly named: they "point" to locations in memory. Think of a row of safety deposit boxes—of various sizes—at a local bank. Each safety deposit box will have a number associated with it, so that the teller can quickly look it up. These numbers are like the memory addresses of variables. A pointer in the world of safety deposit boxes would simply be anything that stored the number of another safety deposit box.
Perhaps you have a rich uncle who stored valuables in his safety deposit box, but decided to put the real location in another, smaller, safety deposit box that only stored a card with the number of the large box with the real jewelery. The safety deposit box with the card would be storing the location of another box; it would be equivalent to a pointer. In the computer, pointers are just variables that store memory addresses, usually the addresses of other variables.
The cool thing is that once you can talk about the address of a variable, you'll then be able to go to that address and retrieve the data stored in it. If you happen to have a huge piece of data that you want to pass into a function, it's a lot easier to pass its location to the function than to copy every element of the data! Moreover, if you need more memory for your program, you can request more memory from the system—how do you get "back" that memory? The system tells you where it is located in memory. In other words, you get a memory address back. And you need pointers to store the memory address.
A note about terms: the word pointer can refer either to a memory address itself, or to a variable that stores a memory address. Usually, the distinction isn't really that important: if you pass a pointer variable into a function, you're passing the value stored in the pointer—the memory address. When some people want to talk about a memory address, they refer to it as a memory address. When they want a variable that stores a memory address, they call it a pointer. When a variable stores the address of another variable, they say that it is "pointing to" that variable.
___________
Pointer Syntax
___________
Pointers require a bit of new syntax because when you have a pointer, you need the ability to request both the memory location it stores and the value stored at that memory location. Moreover, since pointers are somewhat special, you need to tell the compiler when you declare your pointer variable that the variable is a pointer, and tell the compiler what type of memory it points to.
The pointer declaration looks like this:
%26lt;variable_type%26gt; *%26lt;name%26gt;;
For example, you could declare a pointer that stores the address of an integer with the following syntax:
int *pointer1; // points to an integer
Notice the use of the *. This is the key to declaring a pointer; if you add it directly before the variable name, it will declare the variable to be a pointer.
Important: if you declare multiple pointers on the same line, you must precede each of them with an asterisk:
// one pointer, one regular int
int *pointer1, non_pointer1;
// two pointers
int *pointer1, *pointer2;
As I mentioned, there are two ways to use the pointer to access information: it is possible to have it give the actual address to another variable. To do so, simply use the name of the pointer without the *. However, to access the actual memory location, use the *. The technical name for this doing this is 'dereferencing the pointer.' Basically, you're taking the reference to some memory address and following it, to retrieve the actual value. It can be tricky to keep track of when you should add the asterisk. Remember that the pointer's natural use is to store a memory address; so when you use the pointer, i.e., pointer1, then, it evaluates to the address. You have to add something extra—the asterisk (*pointer1)—in order to retrieve the value stored at the address. You'll probably do that an awful lot. Nevertheless, the pointer itself is supposed to store an address, so when you use the bare pointer, you get that address back.
Pointing to Something: Retrieving an Address
In order to have a pointer actually point to another variable it is necessary to have the memory address of that variable also. To get the memory address of a variable (its location in memory), put the %26amp; sign in front of the variable name. This makes it give its address. This is called the address-of operator, because it returns the memory address.
Conveniently, both ampersand and address-of start with 'a;' that's a useful way to remember that you use %26amp; to get the address of a variable.
For example:
#include %26lt;iostream%26gt;
using namespace std;
int main()
{
int x; // A normal integer
int *p; // A pointer to an integer
p = %26amp;x; // Read it, "assign the address of x to p"
cin%26gt;%26gt; x; // Put a value in x, we could also use *p here
cin.ignore();
cout%26lt;%26lt; *p %26lt;%26lt;"\n"; // Note the use of the * to get the value
cin.get();
}
The cout outputs the value stored in x. Why is that? Well, let's look at the code. The integer is called x. A pointer to an integer is then defined as p. Then it stores the memory location of x in pointer by using the address-of operator (%26amp;) to get the address of the variable. Using the ampersand is a bit like looking at the label on the safety deposit box to see its number rather than looking inside the box, to get what it stores. The user then inputs a number that is stored in the variable x; remember, this is the same location that is pointed to by p.
The next line then passes *p into cout. *p performs the "dereferencing" operation on p; it looks at the address stored in p, and goes to that address and returns the value. This is similar to looking inside a safety deposit box only to find the number of (and, presumably, the key to ) another box, which you then open.
Notice that in the above example, pointer is initialized to point to a specific memory address—before it is used. If this was not the case, it could be pointing to anything. This can lead to extremely unpleasant consequences to the program. For instance, the operating system will probably prevent you from accessing memory that it knows your program doesn't own: or else, your program would crash. If it let you use unowned memory, you could mess with the memory of any running program. For example, if you had a document opened in Word, you could change the text! Fortunately, Windows and other modern operating systems will stop you from accessing that memory—by causing your program to crash. To avoid crashing your program, you should always initialize pointers before you use them.
[Side note: It is also possible to initialize pointers using free memory. This allows dynamic allocation of array memory. It is most useful for setting up structures called linked lists.]
The keyword 'new' is used to initialize pointers with memory from free store (a section of memory available to all programs). The syntax looks like the example:
int *ptr = new int;
It initializes ptr to point to a memory address of size int (because variables have different sizes, number of bytes, this is necessary). The memory that is pointed to becomes unavailable to other programs. This means that the careful coder should free this memory at the end of its usage.
The delete operator frees up the memory allocated through new. To do so, the syntax is as in the example:
delete ptr;
After deleting a pointer, it is a good idea to reset it to point to 0. When 0 is assigned to a pointer, the pointer becomes a null pointer, in other words, it points to nothing. By doing this, when you do something foolish with the pointer, you find out immediately—instead of later, when you have done considerable damage.
In fact, the concept of the null pointer is frequently used as a way of indicating a problem—for instance, some functions left over from C return 0 if they cannot correctly allocate memory (notably, the malloc function).
Subscribe to:
Posts (Atom)