C Pointers and Addressing

One of the most potentially confusing, but powerful tools in the C programming language is the amount of control and flexibility a developer has over memory using pointers. Here are a few things that I think every aspiring dabbler or beginner should know about pointers and memory at least at a layman's level.

I don't aim for this article to be 100% exhaustive, but to provide a quick reference or supplementary material for those learning pointers in C.

What is memory (RAM) and is it laid out linearly?

Memory in its simplest form is a big array of bytes and pointers point to bytes in memory. Memory can be contiguous or at least appear linear depending on the memory addressing paradigm.

What is a pointer?

Again so a pointer is a data type (or simply a classification of a type of data) that refers to another value stored in memory by using that value's address.

Referencing and de-referencing?

A pointer references a location (or address) in memory and the opposite is dereferencing. Dereferencing a pointer refers to retrieving the value stored at the location in memory that the pointer refers to.

For example, think of a book with a marker in it on page 100. The book marker is the pointer that references an address (or location) in the book. The value that the book marker "de-references" is the the information contained on that page.

When to use & or * with pointers

Simple right? you use a & operator when referring to an address in memory and a * operator to retrieve the value stored at that address. Right now I am assuming you are lost, so have a look at this example:

  1. int a = 4;
  2. int *b = NULL;
  3. b = &a;

Int A is declared and has a value of 4, and pointer Int B is declared as NULL. Then b references the address of A.

To print the values:

  1.         printf(" int A: %d %p\n", a, &a);
  2.         printf(" int B: %d %p\n", *b, &b);

If you try and print/access a null value, you will get a memory segmentation fault and your application will segfault.

Can I increment a pointer? (simple example of pointer arithmetic)

  1.         char myString[] = "deadbeef";
  2.         char *str_ptr = NULL;
  3.  
  4.         printf("Here is a string: %s\n", myString);
  5.  
  6.         printf("Now lets increment the pointer by 4\n");
  7.         str_ptr = (char *)&myString;
  8.         str_ptr += 4;
  9.         printf("Here is the string after we have incremented it: %s\n",
  10.                str_ptr);

The output from the incremented string should be: beef

However, when incrementing pointers, you should always perform bounds checking to verify that your application is not referencing invalid memory. In other words, if you access information either before or after what your aiming to look at, you will get a memory segmentation fault

How do I pass pointers to functions?

Pointers to variables may be passed through functions a few ways, the easiest is like this:

  1.         struct example_s example_struct = { };  // = {} zeros the structure
  2.         function_1(&example_struct);

And once a pointer has been passed, you can pass that pointer again like so:

  1. void function_1(struct example_s *ex)
  2. {
  3.         // Ignored lines
  4.         function_2(ex);
  5. }

How do I modify pointers that have been passed as parameters in functions?

There are a few older and syntactically correct methods to access and modify a pointer's values. Here is one of the easiest (and cleanest in my opinion):

  1.        // Setting a pointers attribute
  2.         strncpy(ex->b, "ARE", strlen("ARE"));
  3.  
  4.         //If not a pointer
  5.         strncpy(example_struct.a, "POINTERS", strlen("POINTERS"));

Notice the -> and the .

The rule to modifying is: to modify the value of a variable using pointers in a function, you need to pass the address of that variable. - said someone on the Internet.

What is a ** and so on...?

From time-to-time you will see or need to use a double pointer or **. This is commonly done for special data structures (dynamic multidimensional arrays) and returning pointers from functions.

If you look at multidimensional arrays for example - argv can be shown in two different ways. In this case, a double pointer or ** can be used to represent an array of pointers or two dimensional array of strings.

  1. int main( int argc, char **argv)
  2. int main( int argc, char *argv[])

Alternatively, if you want to retain the location of a pointer when passed to a function or to allocate memory for a pointer like in this example, you would use it like so:

  1. void foo( char ** ptr)
  2. {
  3.    *ptr = malloc(255);
  4.    strcpy( *ptr, "This is ground control");
  5. }
  6. int main()
  7. {
  8.    char *ptr = 0;
  9.    // call function with a pointer to pointer
  10.    foo( &ptr );
  11.    printf("%s\n", ptr);
  12.    free(ptr);
  13.    return 0;
  14. }

If you had used only a since *ptr instead of **ptr when calling function foo, the memory that had been allocated would have been lost and a memory leak would have been created. This is because ptr in this case, has a scope limited to only that of its function and the value of ptr would still be zero inside of main. Your goal is to preserve the memory location of the original variable!

I won't explain this further, but stack overflow has some great explanations and so does this link.

  1.        // Assuming other code from example
  2.         int **c = &b;
  3.         printf("\nOkay so what is ** and what does it mean?\n");
  4.         printf
  5.             ("The double pointer points to the single pointer which points to variable A\n");
  6.         printf
  7.             ("You may use the ** to reference the value of the information that is being pointed to\n");
  8.         printf(" int C: %d %p %p %p\n", **c, c, *c, &c);

What is a function pointer?

Function pointers are pointers that point to functions. They are extremely handy and can be used to create clean/functional APIs and callback functions. Much of their use

  1. void our_function(char *str)
  2. {
  3.         if (!str)
  4.                 return;
  5.         printf("Inside out_function()\n");
  6.         printf("string: %s\n", str);
  7. }
  8.  
  9. main() {
  10.         // Define and call our_function()
  11.         void (*fp) (char *);
  12.         fp = &our_function;
  13.  
  14.         fp(myString);
  15.         // Alternately can be called using (*fp)(myString);
  16. }

Example code is attached to this :) Feel free to make any updates, post comments, ideas or questions. Perhaps at a later date I will add more to the more barren sections.

Blog tags: 

AttachmentSize
Pointer example C file3.03 KB

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.