![]() |
|
#1
|
||||
|
||||
[Tutorial] Pointers in C (Part I)Pointers in C: Part I of III
Written by Stack Overflow Introduction Pointers are facile, yet confusing. Thinking in the programming world isn’t easy, and comprehending everything read, intricate. Even though pointers are for the experienced, as they say, I’m here to guide programmers consisting of all levels to greaten their understanding of pointers, and why they are pertinent to your everyday programming. All tutorial examples are Standard C compliant, and should build successfully on any C compiler. All examples are optimized for the -Wall, -pedantic, -ansi, and -std=c89 GCC flags. Pointer Fundamentals Let me start off by stating, a pointer is a variable that contains the address of another variable. Pointers and arrays are closely related, though pointers are sometimes the only way to express a computation. Some also say pointers lead to more compact and efficient code. If you view the following example [1.1], it may be confusing and you’ll see the incompleteness of it: CPP / C++ / C Code:
Pointers and addresses require allocation to store its data. Unlike the char and char[] data types, which use locally stacked memory, pointers pass though existing memory stacks. The unary operator “&” gives the memory address of an existing object. This assigns the address of one variable and “points to” another. Remember, pointers use existing memory, so we can either send a freed block of memory to a pointer, or assign it another variables’ address. Let me lead this with an example: CPP / C++ / C Code:
If you have tried to compile this short example, you may see that it did not result in a crash. This is because we sent our memory address of the variable n to ptr. Here, ptr does not receive its own block of memory, yet it points to an existing variable, n. The same implementation applies in other situations, such as arrays: CPP / C++ / C Code:
Or, you might want to consistently move the pointers position to correspond with all 5 slots of the array {0, 1, 2, 3, 4}. This is called pointer arithmetic, and is very possible to do with ease. An example: CPP / C++ / C Code:
Pointer arithmetic may seem confusing, but it’s just like adding and subtracting. *ptr is the data of your pointer, while ptr is the location. The “++” is an operator that remedies the choice of “+= 1”, or in other terms, “increments the variable by 1”. To reference extended positions, the recommended arithmetic would be “*(ptr+x)” as x represents your incrementing position. Pointers are used in real day-to-day programs. For example, take the following question and convert it to C syntax accordingly: There are 3 people in room A, and 5 people in room B. If the people in each room switched rooms, how many people would be in room A and room B? Note: This seems extremely easy and would best serve if we used pointers in this situation. Let me explain. As logically explained above, we are to swap the people within Room A and Room B, and produce an answer. With our current knowledge of pointers, this can be done feasibly: CPP / C++ / C Code:
As stated in code, void reverse(int *x, int *y) did a simple calculation and reversed A and B. The reason we used a temporary variable was to store the data of x. If we had set “*x = *y” and “*y = *x” it would have caused a problem no matter which we would call first. To break it down, we would literally state “1 [x] = 2 [y]”, then “2 [y] = 2 [x]”. Keeping the previous state of *x was very crucial. Simply, We sent our function void reverse(int *x, int *y) the memory addresses of A and B. That’s where the unary operator comes in handy. Send the addresses of A and B to *x and *y, swap out the two and we’re done. If we had not worked with pointers, we would have to create another set of variables, say, A0 and B0, then send A to B0, and B to A0 yet implementing a swap with unnecessary code congestion. Pointers in the char data type realm We just discussed pointers from the integer perspective, and one-dimensional figures. As we may know, there are multiple dimensions in a programming environment. In which we must take the appropriate steps to accommodate all surrounding aspects. The character array realm is different from the integer, as we must deal with multiple instances in one variable. They both dwindle down to the fact of digits, as the ASCII Table defines. Standard ASCII, and signed char’s represent 0 thru 127. With those numbers, the char reads them as letters, or in the ASCII environment. To explain a character array is in the same mindset: CPP / C++ / C Code:
The example shown is still within the “one-dimensional” environment. Character pointers also need a valid memory address to write to, like integers. Pointing a “character pointer” to a valid memory address isn’t as simple as seen before from the integer perspective. The following can be utilized, but is not recommended by most: CPP / C++ / C Code:
As seen in this example, we initialized text to “Hello” which is 5 letters long resulting {‘H’, ‘e’, ‘l’, ‘l’ ‘o’, ‘\0’} 4 indices in the array system. Arrays always start at 0 and ‘\0’ is at the fifth location, [5]. Next, is a more efficient way of receiving the memory address of a local variable. Even though it’s not recommended, it ensures linkage between the two variables: CPP / C++ / C Code:
Not exactly a two-dimensional pointer. We just need to send a pointer’s address to a function resulting in the pointer’s “*” pointer “*”. In void pointTo(char **, char *); we point dst to the pointed pointer *src. To ensure a pointer has a memory block without risking the chance of our local variable failing, we would take an opposite approach and allocate memory right from your machine's core. Memory allocation in C We previously learned how to link memory addresses to pointers, but now its time to move to a more stable and serious approach: Handling memory from the core. This is no time at all to write a function or algorithm to space partition memory and issue it accordingly. That’s why the ANSI standard incorporated a function within the Standard C Library called void *malloc(unsigned int);. This function works in a unique way, sending the pointer memory of an empty/unused memory blcok of your requested size. This function will fail if there is insufficient memory from the system. Here is an example: CPP / C++ / C Code:
Let’s ask for 6 bytes of memory to work with. If it can’t be found, end the program before a fatal crash occurs. Else, copy 5 letters to our 5 bytes leaving enough room for the NULL terminator ‘\0’. Once we are finished with out memory, we will free it. void free(void *); deallocates any dynamically allocated memory if previously allocated by a call to malloc(). This function is also provided by the standard library stdlib.h. char *strcpy(char *, const char *); is also within the included function(s) written in the standard header files, though this one is declared in string.h. This function, strcpy(), isn’t hard to re-implement. In fact, it just takes a few pointer skills: CPP / C++ / C Code:
Note: Remember, if you have <string.h> included, don’t add these functions to our code example. Library’s and functions will conflict, yet leading to errors. I won’t get into great detail on this function. The main functioning of this is that we increment *src and *s while copying the data from *src to *s while *src still exists. Once done, set the null terminator, and return dest as *s points to it. Multi-dimensional pointers As tricky as it may sound, multi-dimensional pointers are just as easy as one-dimensional pointers, so don’t give up! As opposed to pointers, arrays can also work in a multi-dimensional realm. For example: Lets take: CPP / C++ / C Code:
Code:
That should make a lot of sense. If its too confusing, lets break it down: CPP / C++ / C Code:
Code:
This is beginning to look simpler by the minute. As we previously discussed, the character environment is somewhat different, but not always. Look at this example: CPP / C++ / C Code:
Code:
As seen above, two-dimensional arrays consist of “row” and “column”, as one-dimensional consists of “column”. Allocating memory to two-dimensional arrays can be tricky, so here are some good steps to remember:
CPP / C++ / C Code:
The comments in the code help guide you through each step. The sizeof function comes in handy during this process. We need to multiply our allocation size with the size of our variable to assure we have enough space to allocate anything else. Without that, our program may terminate unexpectedly. Pointers may seem difficult at this point, but its making perfect sense. There comes a time when it begins to advance. I do hope this short tutorial has been helpful to you. Before I’m done, I’d like to explore three-dimensional pointers. This too has a background of difficulty, but in the right perspective it too can be made easy. Three-Dimensional Pointers This is an easy subject I like to think. It’s as easy as 1, 2, 3. Think of this as a Book. A book is three dimensions; depth, row, and column. For example: CPP / C++ / C Code:
Code:
CPP / C++ / C Code:
Code:
I hope this is all coming together. Of course taking special measures for memory allocation is always needed. I’ll show an example: CPP / C++ / C Code:
I’ll let you decipher that one on your own. Always remember; think of this code as a book. Depth, row, and column. Conclusion That concludes this tutorial. In the next tutorial we will discuss Pointers in Application, tips on improving allocation techniques, and briefly explore dynamic allocation of 4-dimensional pointers. In the last tutorial I'll even delve into techniques that will teach you how to dynamically allocate an any-dimensional pointers with a simple concept, and explain contiguous allocation methods. |
||||
|
#2
|
|||
|
|||
|
very good introduction-to-pointers tutorial, Stack Overflow. Only one problem, and one that will frustrate a lot of prospective "students." In Example 2.1, it will either generate a compiler error or, if it does compile, it will crash! The problem is that you declared ca as an array of 3 (three) chars, and then tried to access the fourth one (first: 0, second: 1, third: 2, fourth (uh-oh): 3). Corrected code is shown below.
CPP / C++ / C Code:
|
Recent GIDBlog
Going to Iraq by crystalattice
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| isThere pointers in PHP | sajuat | MySQL / PHP Forum | 1 | 20-Nov-2006 09:18 |
| type* identifier or type *identifier for pointers? | BobbyMurcerFan | C Programming Language | 3 | 07-Dec-2004 07:41 |
| Re: Naming Conventions | WaltP | C Programming Language | 8 | 06-Jun-2004 22:22 |
| Help with C++ pointers | Mjkramer21 | CPP / C++ Forum | 23 | 18-Apr-2004 07:53 |
| Passing Pointers To Pointers in Functions | elumira | C Programming Language | 8 | 05-Mar-2004 21:23 |
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The