1/11/2012

NCC Tutorial: Pointers Exercise

As usual, theoretical knowledge on some subject is nothing if you don't know how to apply it to some practical problem. So, in this post we will try to summarize and combine all the stuff we learned in this tutorial.

Notice: you may wish to (re-)read other parts of this tutorial:
  1. Basic pointers principle,
  2. Using pointers for variables manipulation,
  3. The connection between pointers and arrays,
  4. Using pointers as function arguments.
Now, when you know everything you need to know, it's time to use it.

Let's make an array manipulation program. It should have specific functions for some basic tasks: find the maximum element, find the first occurrence of some element, remove all occurrences of some element, and replace the second occurrence of an element with its opposite number. Additional requirement: 'find' functions return types are pointers to the specific positions in the array, or NULL if specified element is not found.

Now, note that you will use integer array. Also, in scanf, as you now know, you will use referencing operator for variable input. Additional argument in every function should be the size of the array. Having all this on mind, here's some brief code:
int *find_max(int a[], int n)
{
  int *p = a, i;
  for (i=1; i<n; i++)
    if (a[i]>*p)  // *(a+i)
      p = &a[i];  // p=a+i
  return p;
}

int *find_first(int a[], int el, int n)
{
  int i=0;
  while (i<n) {
    if (a[i] == el)
      return &a[i];
    ++i;
  }
  return NULL;
}

void *remove_all(int a[], int el, int *n) 
// n is subject to change
{
  int i, j=0;
  for (i=0; i<n; i++) {
    if (a[i]==el)
      continue;
    a[j] = a[i];
    j++;
  }
  *n = j;
} // notice: this will overwrite old array a

void replace_second(int a[], int subj, int repl, int n)
{
  int *old = a;
  a = find_first(a, subj, n);
  if (a==NULL) 
    return;
  a++;
  n-=(a-old);
  a = find_first(a, subj, n);
  if (a==NULL)
    return;
  *a = repl;
}
Great. You should check this out and see if it works for you. If it doesn't, try to find errors and fix them. Also, if it doesn't, tell me what bugs you found. I won't tell you if this really works as it should, because you need to understand the code, how it works and why it works (or doesn't) like expected.

I think this is a nice example of all the stuff with pointers we worked on in this tutorial. If you have any questions or comments, please feel free to say something down there. I am ready to start a conversation with you. No matter what, keep on practicing, that's all you really have to do if you want to learn any language.

No comments:

Post a Comment

If you have anything useful to say (ideas, suggestions, questions, business proposals, or just "Thank you!"), please feel free to comment! Also, you can use my e-mail and/or find me on Twitter!