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[].

 

Print Friendly

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">