answersLogoWhite

0


Best Answer

Pointers are variables. They allow you to store memory addresses and to indirectly manipulate the contents of those memory addresses. Pointers can point to variables, constants and functions -- anything that resides in memory -- so long as the type of the pointer is covariant with the type being pointed at. Pointers that are no longer in use should be nullified by assigning the value NULL, thus preventing indirect access to memory that may no longer be in scope.

In C, a pointer is no different to a reference, hence we use the term 'dereference' when indirectly accessing the value of a pointer (the memory being pointed at). But in C++, a reference is not a variable of any kind, it is simply an alias that you can use in your source code to refer to an instance of an object, function, variable or constant. C++ references must be initialised at the point of instantiation, and are not unlike constant pointers. However, unlike references in C, references in C++ can never be NULL (a NULL reference will invalidate your program).

User Avatar

Wiki User

10y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

10y ago

A pointer is nothing more than a 32-bit unsigned variable that is used specifically to store a memory address (in 64-bit architecture, a pointer is 64-bits long), and which can be used to access that memory indirectly. The type of pointer determines how that memory is to be treated. Pointers are quite similar to references, however a reference is simply an alias for a variable and therefore requires no additional storage of its own. More importantly, references cannot be re-assigned. Pointers are little more difficult to use, but offer a greater flexibility than references.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

While references are easier to program than pointers, pointers are more flexible than references. Plus there are certain runtime tasks that cannot be done with references alone, such as dynamic object creation and dynamic memory allocation.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

Pointers are important in C++ for a number of reasons -- not least to ensure backward-compatibility with C. Although OOP languages do not have any concept of pointers, C++ is not a fully object-oriented language. While it fully supports the OOP paradigm, it retains the concept of primitive integrals, including pointers, which are not implemented as objects. As such it is a hybrid language.

Pointers are necessary for reasons other than backward-compatibility. For instance, while C pointers and references are the same thing, a C++ reference is quite different to a C++ pointer. For one thing, a C++ reference can never be NULL (a NULL reference will completely invalidate your program). Thus when instantiating new objects dynamically, it would not be possible to return a reference if there were insufficient resources to meet the allocation; you'd end up with a NULL reference and an invalid program. Thus the C++ new keyword returns a pointer, because pointers can be NULL. This is why you must always test for NULL before dereferencing a pointer. Once you have a non-NULL pointer, you can reference the memory it points to.

Note that a C++ reference is merely an alias, an alternate name, for an existing allocation. Pointers are variables and thus require memory of their own (to store the address they refer to) but references are not variables in their own right. That is, if you have an int, x, and you assign x to an integer reference, y, anything you do to y is reflected in x, because x and y both refer to the same variable. In other words, they are the same variable by different names, just as Billy is an alternate name for William. With pointers, Billy is a completely separate entity to William, such that William is the object itself, while Billy simply contains the address of William. Thus dereferencing Billy returns a reference to William. That reference can then be assigned to Bill, or Will, or indeed both. Thus Bill, Will and William are all references to the same object, but Billy is not. It is a reference to a pointer.

Pointers are also fundamental to arrays. The array name is a reference to the start address of the array, the location of the first element in the array. Normally you use the array subscript operator [] to access individual elements in the array, but behind the scenes you are actually performing simple pointer arithmetic. That is, element [2] can be found at address 2*sizeof(x) bytes from the start of the array, where x is the size of each element. Thus, for an array of int, element 2 will be found at address 2*sizeof(int). The subscript operator is merely sugar-coating for this underlying pointer arithmetic.

By the same token, if you hold a pointer to any element in the array, and the pointer is the same type as the array elements, then incrementing the pointer by 1 will automatically point to the next element. In other words, an int pointer is incremented by sizeof(int) bytes. If you use a pointer of a different type, then you do not advance by 1 element, you advance by sizeof(type) instead.

This aspect of pointer manipulation makes it possible to remap memory. For instance, a pointer of type char can be used to step through the individual bytes of long integral. Thus a 32-bit integral can be treated as if it were really 4 individual bytes, or two shorts.

Pointers can also be used to pass objects into functions by reference. Normally, a function will accept a reference rather than a pointer, but references are only useful when the object being passed is guaranteed to be non-NULL. Pointers are more flexible in that object parameters can be optional rather than mandatory. Hence functions that accept pointers often default those parameters to NULL, to indicate that no object is being passed.

Pointers are also important in complex structures such as lists and trees, since each element in the structure must point to the next sibling, the first child, or the parent element. With these structures, unlike an array, it is not necessary to reallocate the entire structure to add or remove elements, you simply update the pointers within the structure itself. This allows large structures to grow and shrink far more efficiently, because the order is determined by the elements themselves. In an array, the order is determined by the physical order of the elements within the array, where all elements are stored in contiguous memory. With complex structures, the elements need not be contiguous, nor must they be in any particular order. The last element can easily be allocated in lower memory than the first element, you simply follow the chain of pointers from one element to the next to determine the actual order.

Ultimately, pointers and references do pretty much the same job, but pointers are more flexible than references. That flexibility comes at a cost in that they are slightly more difficult to work with and use more memory. References are easier to work with since they can never be NULL, cannot be reassigned (much like a constant pointer), and do not require dereferencing. But their inflexibility means they are not suitable for every operation, not least as a return value from the new operator.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

A pointer is simply a variable that is used to both store a reference and to provide indirect access to that reference's value. Although you will generally use references without using pointers, you cannot use pointers without references. Therefore before we can fully explain what a pointer is, we must first clarify exactly what we mean by a reference.

What is a reference?

Put simply, a reference is an alias for a memory address. However, we cannot arbitrarily refer to just any memory location, there has to be a pre-existing object at the memory location before we can physically refer to it. The object must be a variable (which includes constants) or a function (which includes class member methods).

We declare references in the same way we declare variables, however references are not variables in any sense of the word. No memory is allocated to a reference; it is simply a named value that refers to an existing value, nothing more. Consider the following:

int var = 321;

int& ref = var;

Here we've declared an int variable, var, and initialised it with the value 321. We've subsequently declared a reference, ref, and assigned var to it. Note the use of the unary reference operator (&).

It's easy to imagine that ref is a completely separate variable to var, but it is not a variable. We can prove this by examining the memory addresses assigned to var and ref:

printf( "var @ 0x%.8x = %d\n", &var, var );

printf( "ref @ 0x%.8x = %d\n", &ref, ref );

Note that the & represents the unary address-of operator, which returns the address of the operand. The reference operator and address-of operator are directly related, hence they use the same symbol.

Example output:

var @ 0x0010abcd = 321

ref @ 0x0010abcd = 321

Perhaps surprisingly, both var and ref appear to be sharing the exact same memory address! This is not as impossible as it sounds because ref is simply an alternate name for var, an alias, it is not a variable in its own right.

This means that if we were to change the value of ref, we change the value of var, and vice versa. They are one and the same value after all.

Normally we wouldn't refer to a local variable with a local reference like this. If the variable is local we can obviously access it directly without referring to it. However, we can use references to statically cast variables from one type to another. For instance:

char& cref = var;

printf( "cref @ 0x%.8x = %c (%u)\n", &cref, cref, cref );

Example output:

cref @ 0x0010abcd = A (65)

Here we've statically cast the int var to a char and obtained the value 65 (the ASCII character code for A). In memory, the integer value 321 appears as bit sequence 01000001 00000001 00000000 00000000 (in little-endian order). cref refers only to the first byte (because a char is only 1 byte in length) which is 65 in decimal.

While references are certainly handy for static casting tricks like this, they are far more useful when it comes to passing values to functions. By default, arguments are passed by value, which means the function copies the argument and assigns the value to the appropriate parameter:

int ByVal(int byval) {

printf( "byval @ 0x%.8x = %d\n", &byval, byval );

return( byval *= 2 ); }

Example output from calling ByVal(var):

byval @ 0x0010bcde = 321

Here we can clearly see that the parameter byval has a different address to the argument var, proving the argument was automatically copied. For variables of type int or smaller, there's no real overhead in copying the argument. However, if we want to update var via this function, we'd have to assign the return value to var:

var = ByVal(var);

If this were the only way to update arguments to functions, our programs would quickly become bogged down with copy and assign operations. Fortunately, references can save the day for us:

void ByRef(int& byref) {

printf( "byref @ 0x%.8x = %d\n", &byref, byref );

byref *= 2; }

Example output from calling ByRef(var):

byref @ 0x0010abcd = 321

Now we no longer need a return value because byref references var and is therefore an alias for var. What we've really done is pass the address of var into the function (because it expects a reference, not a value), which the function assigned to the byref reference parameter.

Passing by reference becomes extremely useful when dealing with large and complex objects. If we pass them by value, they will be copied. But if a function does not alter the value, there is no need to copy the object at all. We can simply declare the reference parameter as being a constant.

Useful as references are, they have a few limitations. The first is that they cannot be re-assigned while they remain in scope. Consider the following:

int var = 321;

int& ref = var;

int x = 666;

ref = x; // re-assign to reference x?

printf( "var @ 0x%.8x = %d\n", &var, var );

printf( "ref @ 0x%.8x = %d\n", &ref, ref );

Example output:

var @ 0x0010abcd = 666

ref @ 0x0010abcd = 666

If you expected ref to now refer to x and for var to remain unaffected, then the output might surprise you. However, ref = x is not assigning x to the reference, it is assigning the value of x to the reference. Thus the value 666 is assigned to ref. But since ref is still referencing var, var now has the value 666. To repeat: references cannot be re-assigned while they remain in scope.

The second limitation is that references can never be NULL. To understand this concept, we need to discuss pointers. However, you now know exactly what a reference is so understanding pointers should be a little easier to grasp.

What are pointers?

As mentioned at the beginning of this answer, a pointer is a variable. Remember that references are not variables, but pointers are. Pointers effectively allow us to store references. To look at it another way, pointers allow us to convert references into variables.

Since a reference is simply an alias for a memory address, pointers really store memory addresses. So, just as we can access variables by referencing them, we can access those same variables through pointers to them. In effect, anything we can do with a reference, we can do with a pointer. The only cost in using a pointer is that it requires 4 bytes of memory to store the memory address (or 8 bytes on a 64-bit system).

Let's begin by declaring a pointer:

int var = 321;

int* ptr = &var;

Note that the asterisk tells the compiler that we are instantiating a pointer variable (of type int) and that the address-of operator is required in order to store the reference to var.

printf("ptr @ 0x%.8x => 0x%.8x = %d\n", &ptr, ptr, *ptr );

Note that we have three pieces of information we can access via pointers. The first is the address of the pointer variable, the second is the reference stored in that address (the pointee) and the third is the value of the reference, which is accessed with the unary dereference operator (*).

Example output:

ptr @ 0x0010cfef => 0x0010abcd = 321

Since pointers store references, we can pass pointers into functions that expect a pointer, and they will act as if they were passed a reference. Why not simply pass a reference? The only reason to accept a pointer rather than a reference is to cater for the possibility that no such object exists. Remember, references can never be NULL, but pointers can. A NULL pointer is simply one that contains the value zero (synonymous with the constant NULL).

To understand NULL pointers we must now look at dynamic memory allocation, which can only be achieved through pointers. Consider the following pointer declaration:

int * ptr = new int(321);

The C++ new operator is used to allocate memory of the given type upon the heap (or free store). The return value is a pointer to the start address of that memory. All primitive data types support the new operator, as do all classes of object that have at least one public constructor besides a copy constructor.

Dynamic allocations such as this can only succeed if there's a free block of memory large enough to accommodate the requested type. In this case we're only asking for 4 bytes of memory (assuming an int is 4 bytes long), so it's highly unlikely this allocation will fail. But that doesn't mean it won't. Highly-complex objects will often require much more memory and sooner or later you will encounter a failure. When this happens, the new operator returns the value zero (NULL).

Therefore, before you attempt to access the reference within a pointer, you must ensure the reference is non-zero. If so, you can begin working with your new object. However, it is vital that you do not re-assign the pointer or nullify it. The memory you allocated must be released as soon as you're finished with it and the only way to do so is via the pointer. You may copy the pointer and re-allocate the original, however all dynamic allocations must be released at some point (sooner rather than later). This is achieved with the delete operator:

delete( ptr );

It is good practice to always nullify a pointer after deleting it:

ptr = NULL;

You will often encounter code where pointers are not nullified. While it's not considered "polite", there are two instances where nullifying a pointer is redundant. The first is when the pointer falls from scope immediately after the deletion. The second is when the pointer is immediately re-allocated.

Earlier I mentioned that references cannot be re-assigned. But pointers can be re-allocated:

int * ptr = new int(321);

// do some work with ptr

delete( ptr );

ptr = new int(666);

// do some more work with ptr

delete( ptr );

ptr = NULL;

// finished with ptr for good.

The fact pointers can be NULL and that they can be re-allocated fills the gap left by references. Most of the time you will use references as they are so much easier to deal with, but if there's even the slightest possibility a reference does not exist, you must use a pointer.

While pointers and references have many similarities and are interchangeable to a degree, some tasks are best suited solely to pointers. Dynamic memory allocation is one such task. Linked lists are another.

Linked lists are data containers that contain zero or more nodes, where each node contains a data element. Each node also has a pointer that refers to the next node in the container. Thus the container need only keep track of the first node, known as the head node. If the head node is NULL, the container is empty. Otherwise, the head node points to the second node, which points to the third, and so on. The last node (the tail node) has no next node so its pointer will be NULL.

Inserting new nodes is achieved by copying the preceding node's next pointer into the new node, and pointing the preceding node to the new node. Removing a node simply requires that the preceding node points to the next node of the node being extracted. Ultimately, there is no need to move elements around in memory to change the order of nodes -- you simply adjust the pointers.

Doubly-linked lists have nodes that contain two pointers, one to the next node, the other to the previous node. The container usually keeps track of the tail node as well as the head node, thus allowing bi-directional traversal of the list from either end. Insertions and extractions require a little more work to adjust pointers on either side of a node, but otherwise the principal is the same as for a linked list.

Circular lists are doubly-linked lists where the tail node's next node is the head node, and the head node's previous node is the tail node.

All of these list models rely heavily upon pointer manipulation. While random access is better achieved with an array, linked lists offer dynamic expansion and contraction and constant time access to the head of the list, none of which would be possible without pointers.

Pointers and references also lie at the heart of arrays:

int s[10];

Both s and &s return the same value, the starting address of the entire array. s is therefore a reference. Perhaps less obvious is the use of the index operator []. When we access an element in an array, such as s[3], the underlying mechanism is using pointer arithmetic to navigate to the appropriate offset from s, which is quite literally s + ( 3 * sizeof(s[0])).

Pointers can also point at other pointers (which can themselves point to other pointers). These are known as pointer-to-pointer types, which introduces an extra level of indirection. However, multi-dimensional dynamic arrays would not be possible with them. For instance, a two-dimensional array is constructed by maintain a pointer-to-pointer to a dynamic array of pointers, each of which refers to a separately allocated one-dimensional array of elements. A three dimensional array requires a pointer-to-pointer-to-pointer to an array of pointer-to-pointer, each of which refers to an individually allocated two-dimensional array as previously mentioned. And so on. If the array is fairly small, the entire array can be made in contiguous memory with a single allocation, and then the pointer arrays are adjusted to divide that memory as you see fit. None of this would be possible without pointers.

Pointers can also point at functions. A function's name is simply a reference to its memory location. As such it can be pointed at. This then makes it possible to pass functions as arguments to other functions.

As you can appreciate, pointers are highly flexible and have many uses well beyond those covered here. Ultimately, anything you can do with a reference you can also do with a pointer, and then some. However, references are much easier to work with and you are actively encouraged to use them as much as is possible. Pointers are a bit more complex, but in certain situations there really is no alternative. The guiding factor is that if a reference could be NULL, regardless of how unlikely, then you must use a pointer. Otherwise use a reference. Remember that pointers are variables and they will consume memory of their own. And the onus is always upon you, as programmer, to keep track of your pointers and ensure any dynamic memory allocated to a pointer is released as soon as it is no longer required.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

stores the address of a variable and consumes only those memory which has been validated last..

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Why are pointers important in C plus plus?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

Difference between array and pointers in c plus plus?

A pointer is simply a variable that can store a memory address and has the same purpose in both languages. The only real difference is that C++ pointers can point at objects (instances of a class) and indirectly invoke their methods, whereas pointers in C (which is not object oriented) cannot.


What is pointer to an object in c plus plus?

A pointer is simply a variable that stores a memory address. Thus a pointer to an object is simply a variable that stores the memory address of an object. Since pointers are variables, they require memory of their own. Pointers may also be constant, which simply means you cannot change what they point to. Pointers can also be dereferenced to provide indirect access to the memory they point to -- hence they are known as pointers. However, unlike C, pointers are not the same as references. In C++, a reference is simply an alias for a memory address and requires no storage of its own.


Why pointer is callded jewel of c language?

a pointer is a derived data type in c. pointers are undoubtedly one of the most distinct and exciting features of c language.it has added power and flexibility to the language. *pointers are more efficient in handling arrays and tables. *pointer can be used to support dynamic memory management. *pointers reduce length and complexity of programs. *increase the execution speed and thus reduce the program execution time. by following character's real power of c lies in proper use of pointers. pointer is called the jewel of c-language.


Initialization of variables in namespace in C plus plus?

Is an important thing to do.


In C you use the concept of pointers whereas there are no pointers used in JAVA why?

Pointers in C are generally the thing that gives learners the most trouble. When C code is not written correctly with respect to pointer use, the resulting bugs can often be very difficult to find and correct. On the other hand, pointers are absolutely necessary in some cases.The designers of Java wanted to make programming easier and hence avoided adding pointers to the language. Java does have object references which accomplish much of what pointers accomplish albeit in a safer way.

Related questions

What is the difference between c plus plus and java programming?

Java doesn't have pointers. C++ has pointers.


What is the difference between pointers in c and c plus plus?

Nothing.


Is it possibly to return an array of strings in a function without using pointers in C plus plus?

No.


What are the storage allocation in C plus plus?

They mostly deal with pointers and new operators in memory.


How do you write a reverse function in C plus plus without pointers?

You can either use references or you can simply return the result by value. Note that in C++, unlike C, references are not the same as pointers. C++ references are aliases, alternate names for existing objects, whereas pointers are just variables that may contain a memory address that can be dereferenced.


Do you have pointer concept in c plus plus language?

Yes. All string variables are pointers as are other arrays.


Difference between array and pointers in c plus plus?

A pointer is simply a variable that can store a memory address and has the same purpose in both languages. The only real difference is that C++ pointers can point at objects (instances of a class) and indirectly invoke their methods, whereas pointers in C (which is not object oriented) cannot.


What does multiplying a pointer by 5 in C plus plus mean How does it change the pointer's value?

Multiplication is yet another thing, what you should never do with pointers.


What is meant by passing function to another function in c plus plus?

Just as pointers can point to variables, pointers can also point to functions. Thus you can pass function pointers to functions. In so doing, you can alter the behaviour of the function by having it call dynamically call arbitrary functions rather than just preset functions.


What is pointer to an object in c plus plus?

A pointer is simply a variable that stores a memory address. Thus a pointer to an object is simply a variable that stores the memory address of an object. Since pointers are variables, they require memory of their own. Pointers may also be constant, which simply means you cannot change what they point to. Pointers can also be dereferenced to provide indirect access to the memory they point to -- hence they are known as pointers. However, unlike C, pointers are not the same as references. In C++, a reference is simply an alias for a memory address and requires no storage of its own.


What is stream pointer in c?

C does not have stream pointers.


Why pointer is callded jewel of c language?

a pointer is a derived data type in c. pointers are undoubtedly one of the most distinct and exciting features of c language.it has added power and flexibility to the language. *pointers are more efficient in handling arrays and tables. *pointer can be used to support dynamic memory management. *pointers reduce length and complexity of programs. *increase the execution speed and thus reduce the program execution time. by following character's real power of c lies in proper use of pointers. pointer is called the jewel of c-language.