Why do pointers exist




















C uses pointers to handle variable parameters passed to functions. Pointers in C provide an alternative way to access information stored in arrays. Pointer techniques are especially valuable when you work with strings. There is an intimate link between arrays and pointers in C. Cite This! Print Citation. Try Our Crossword Puzzle! What Is the Missing Number? Try Our Sudoku Puzzles! More Awesome Stuff. If you look into the code of virtually any program, you will easily notice that pointers are everywhere.

Pointers allow us, among other things, to process dynamic data structures; to deal with memory, strings, arrays; to efficiently pass arguments to functions, including parameters that are themselves functions Pointers to functions are a special type of pointers, that we will discuss in section on functions. For pointers, it is the address of another variable in computer memory. This another variable can be of any type; in particular, it can be a pointer variable itself.

Usually, although not always, we have to specify the type of variables whose address can be assigned to a newly created pointer variable. This makes it possible for compilers to perform type checking; it also allows for some operations on pointers, as for their completion information about the size of variables ponted to by pointers is required.

Values stored in pointer variables are addresses of other variables. Suppose we want to create a pointer suited to store addresses of other variables which are of type double. Then we want to assign values to these pointers, i. Let's see how to do it considering the following example: P 15 : pointers. One of them, y , is initialized with the value 1.

After this line has been executed, the pointer px exists but has no particular value. It does not point to any variable. This notation means that a variable named px will be a pointer which can store as its value addresses of variables of a type Type.

How can we assign a value to px? We see an example on line 8. This line assigns the value of the expression on the right hand side of the equality sign to the pointer on the left hand side. The value of the expression on the right hand side is just what we need: the address of an existing double variable, in this case of the variable x. The variable x exists because it was created on line 5; it has no well defined value, but it does have a well defined address.

For this to be possible, the expression on the right hand side of the address operator must be an l-value see the section on l-values. Therefore, the value of py is the address of y , while the value of y is 1. This situation is illustrated in the figure. The variable py exists in the memory under some address — in the example it is 0xbffffa18 addresses are usually written in hexadecimal notation. This variable occupies 4 bytes, although this can depend on platform. The value stored under this address, i.

This variable occupies 8 bytes and stores the value of y : a number. Find centralized, trusted content and collaborate around the technologies you use most. Connect and share knowledge within a single location that is structured and easy to search.

Short answer is: Don't. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below Short answer here is: Where you cannot use anything else.

In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here. With little effort and much confusion. These declarations are very similar but not the same - e. Now we are using the character itself instead. And this is where things start to get dangerous.

This would print whatever is found on memory address and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments.

Imagine the problems you might cause if you were to use sprintf instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated.

You would most likely end up writing over something else in the memory and cause your program to crash if you are lucky. Using malloc, calloc or similar. So here's a few examples:. Do note that you can still use the variable x after you have performed a free of the allocated memory, but you do not know what is in there. Also do notice that the two printf might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.

One reason to use pointers is so that a variable or an object can be modified in a called function. This makes it easy to change the way the calling function receives the value without having to modify the semantics of passing it. Pointers are one way of getting an indirect reference to another variable. Instead of holding the value of a variable, they tell you its address. This is particularly useful when dealing with arrays, since using a pointer to the first element in an array its address you can quickly find the next element by incrementing the pointer to the next address location.

Pointers are similar to references. In other words, they're not copies, but rather a way to refer to the original value. Before anything else, one place where you will typically have to use pointers a lot is when you're dealing with embedded hardware.

Maybe you need to toggle the state of a digital IO pin. Maybe you're processing an interrupt and need to store a value at a specific location. You get the picture. However, if you're not dealing with hardware directly and are just wondering about which types to use, read on.

Why use pointers as opposed to normal variables? The answer becomes clearer when you're dealing with complex types, like classes, structures and arrays. That will work just fine and if you don't know exactly why you're using pointers, you shouldn't use them. Beware of the "they're probably faster" reason. Run your own tests and if they actually are faster, then use them. However, let's say you're solving a problem where you need to allocate memory.

When you allocate memory, you need to deallocate it. The memory allocation may or may not be successful. This is where pointers come in useful - they allow you to test for the existence of the object you've allocated and they allow you to access the object the memory was allocated for by de-referencing the pointer.

This is the key to why you would use pointers - references assume the element you're referencing exists already. A pointer does not. The other reason why you would use pointers or at least end up having to deal with them is because they're a data type that existed before references.

From a maintainability point of view, I should also mention that when you do use pointers, you either have to test for their validity and handle the case when they're not valid, or, just assume they are valid and accept the fact that your program will crash or worse WHEN that assumption is broken. Put another way, your choice with pointers is to either introduce code complexity or more maintenance effort when something breaks and you're trying to track down a bug that belongs to a whole class of errors that pointers introduce, like memory corruption.

So if you control all of your code, stay away from pointers and instead use references, keeping them const when you can. This will force you to think about the life times of your objects and will end up keeping your code easier to understand. Just remember this difference: A reference is essentially a valid pointer. A pointer is not always valid.

So am I saying that its impossible to create an invalid reference? It's just harder to do unintentionally and you will be amazed at how many bugs are unintentional :. Basically, the standard CPU architecture is a Von Neumann architecture, and it's tremendously useful to be able to refer to the location of a data item in memory, and do arithmetic with it, on such a machine. If you know any variant of assembly language, you will quickly see how crucial this is at the low level.

One use of pointers I won't mention things already covered in other people's posts is to access memory that you haven't allocated.

This isn't useful much for PC programming, but it's used in embedded programming to access memory mapped hardware devices. Back in the old days of DOS, you used to be able to access the video card's video memory directly by declaring a pointer to:. Since they're the address of an item, they're small: they take up only the space of an address. Since they're small, sending them to a function is cheap. And then they allow that function to work on the actual item rather than a copy.

If you want to do dynamic storage allocation such as for a linked-list , you must use pointers, because they're the only way to grab memory from the heap. Pointers are important in many data structures whose design requires the ability to link or chain one "node" to another efficiently. You would not "choose" a pointer over say a normal data type like float, they simply have different purposes.

The address of the first element in your array can be assigned to a pointer. This then allows you to access the underlying allocated bytes directly. The whole point of an array is to avoid you needing to do this though. One way to use pointers over variables is to eliminate duplicate memory required. For example, if you have some large complex object, you can use a pointer to point to that variable for each reference you make.

With a variable, you need to duplicate the memory for each copy. Really, when you think about it, this makes sense. When you use subtype polymorphism, ultimately, you don't know ahead of time which class's or subclass's implementation of the method will be invoked because you don't know what the actual class is.

Note: if a class has 5 instance fields versus 3, more space will need to be allocated. The need for pointers in C language is described here.



0コメント

  • 1000 / 1000