Yet Another Introduction to C Pointers

Pointers are memory locations that store other memory locations. Pointers are not a data type in the same sense that char, int, and double are data types. Pointers provide access to another data type, rather than being a data type in and of themselves.

#include <stdio.h>

int main(void){
 
  //declare some basic data types
 
  char charExmp;
  int intExmp;
 
  /*
   * declare a pointer
   *specify the data type that
   *will be pointer to
   *and put an asterisk in front of the
   *variable's identifier
  */
  char *charPtr;
  int *intPtr;
  void *voidPtr;
 
  return 0;
 
}

When we assign a value to a pointer, we must only assign an address. To assign an address we use the address of operator, the ampersand symbol to access the memory address of the variable. The compiler sets aside the amount of memory for a variable when it is declared, so we can be sure that declared variables have addresses.

#include <stdio.h>


int main(void){
 
  char charVal;
  double doubleVal;
 
  char *charPtr;
  double *doublePtr;
  void *voidPtr;
 
  //use the assignment operator
  //followed by the address of operator
  charVal='h';
  charPtr = &charVal;
 
  printf("charVal is %c.\n", charVal);
  printf("the address of charVal is %p\n", &charVal);
  printf("the value stored in charPtr is %p\n", charPtr);
 
  doubleVal = 918.664;
  doublePtr = &doubleVal;
 
  printf("doubleVal is %f.\n", doubleVal);
  printf("the value pointed to by doublePtr is %f\n", *doublePtr);
 
 
  return 0;
 
}

The dereference operator is the same as the asterisk used to declare a pointer. When used outside of a declaration, the asterisk is a dereference operator that tells the compiler to access the value stored where the pointer is pointing to.

#include <stdio.h>

int main(void){
 
 
  int intSrc, intDest;
 
  int *intPtr;
 
  intSrc = 2600;
 
  intPtr = &intSrc;
 
  intDest = *intPtr;
 
  printf("intDest has the value %d\n", intDest);
 
   return 0;
 
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s