Using Pointers as Array Names

It made me very excited that some students reported taking my advice to “test things out in the small” by writing programs to evaluate nebulous ideas in C programming. They reported to me that something we discussed in class wasn’t accurate, so this post brings you an update on it.

When you try to use a pointer as an array name, after having assigned it a chunk of memory dynamically allocated, you can use the indexing square brackets to get to individual characters, as in the lines marked (1) in the program below. If you try to deference the pointer first and then index into the array, as in the lined marked (2) below, you get compile time errors. Note that to get this program to compile, you have to comment out the lines marked (2) or remove them from the program altogether.

As you can see, it’s easy to goof when playing with pointers in C. Do as these students did and try things out as much as possible before you accept them as facts. The punchline here is that your professors can makes mistakes, too!

Another interesting point you can learn from this program is that if you are not going to use command line parameters in your code, you can use argument void in your main function. This saves you a bit of typing the boiler plate code int argc, char* argv[].

 

#include 
#include 

int main (void) {
  char *something; // declare a pointer to character
  something = malloc(3*sizeof(char)); // allocate space for a string
  something[0] = 'h'; // (1)
  something[1] = 'i'; // (1)
  something[2] = 0; // (1) add null terminator to make this a real C string
  printf("no dereference: %s\n",something); // 

  char *something_else;
  something_else = malloc(4*sizeof(char));
  (*something_else)[0] = 'b'; // (2)
  (*something_else)[1] = 'y'; // (2)
  (*something_else)[2] = 'e'; // (2)
  (*something_else)[3] = 0; // (2)
  printf("dereference: %s\n",(*something_else));
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.