30 March, 2007

Pointers in C

Pointer is a complicated, often confusing definition in C programming. Here is an article that probably help you understand pointer in C programming much better !



Pointers


Objectives:

Having read this section you should be able to:

1.program using pointers
2.understand how C uses pointers with arrays


Point to Point:

Pointers are a very powerful, but primitive facility contained in the C language. Pointers are a throwback to the days of low-level assembly language programming and as a result they are
sometimes difficult to understand and subject to subtle and difficult-to-find errors. Still it has to be admitted that pointers are one of the great attractions of the C language and there will be

many an experienced C programmer splutering and fuming at the idea that we would dare to refer to pointers as 'primitive'!

In an ideal world we would avoid telling you about pointers until the very last minute, but without them many of the simpler aspects of C just don't make any sense at all. So, with apologies,
let's get on with pointers.

A variable is an area of memory that has been given a name. For example:

int x;

is an area of memory that has been given the name x. The advantage of this scheme is that you can use the name to specify where to store data. For example:

x=lO;

is an instruction to store the data value 10 in the area of memory named x. The variable is such a fundamental idea that using it quickly becomes second nature, but there is another way of
working with memory.

The computer access its own memory not by using variable names but by using a memory map with each location of memory uniquely defined by a number, called the address of that
memory location.

A pointer is a variable that stores this location of memory. In more fundamental terms, a pointer stores the address of a variable . In more picturesque terms, a pointer points to a variable.

A pointer has to be declared just like any other variable - remember a pointer is just a variable that stores an address. For example,

int *p;

is a pointer to an integer. Adding an asterisk in front of a variable's name declares it to be a pointer to the declared type. Notice that the asterisk applies only to the single variable name that it
is in front of, so:

int *p , q;

declares a pointer to an int and an int variable, not two pointers.

Once you have declared a pointer variable you can begin using it like any other variable, but in practice you also need to know the meaning of two new operators: & and *. The & operator

returns the address of a variable. You can remember this easily because & is the 'A'mpersand character and it gets you the 'A'ddress. For example:

int *p , q;

declares p, a pointer to int, and q an int and the instruction:

p=&q;

stores the address of q in p. After this instruction you can think of p as pointing at q. Compare this to:

p=q;

which attempts to store the value in q in the pointer p - something which has to be considered an error.

The second operator * is a little more difficult to understand. If you place * in front of a pointer variable then the result is the value stored in the variable pointed at. That is, p stores the

address, or pointer, to another variable and *p is the value stored in the variable that p points at.

The * operator is called the dereferencing operator and it helps not to confuse it with multiplication or with its use in declaring a pointer.

This multiple use of an operator is called operator overload.

Confused? Well most C programmers are confused when they first meet pointers. There seems to be just too much to take in on first acquaintance. However there are only three basic ideas:

1.To declare a pointer add an * in front of its name.
2.To obtain the address of a variable us & in front of its name.
3.To obtain the value of a variable use * in front of a pointer's name.

Now see if you can work out what the following means:


int *a , b , c;
b = 10;
a = &b;
c = *a;


Firstly three variables are declared - a (a pointer to int), and b and c (both standard integers). The instruction stores the value l0 in the varable b in the usual way. The first 'difficult'

instruction is a=&b which stores the address of b in a. After this a points to b.

Finally c = *a stores the value in the varable pointed to by a in c. As a points to b, its value i.e. 1O is stored in c. In other words, this is a long winded way of writing

c = b;

Notice that if a is an int and p is a pointer to an int then

a = p;

is nonsense because it tries to store the address of an int, i.e. a pointer value, in an int. Similarly:

a = &p;

tries to store the address of a pointer variable in a and is equally wrong! The only assignment between an int and a pointer to int that makes sense is:

a = *p;


Swap Shop:

At the moment it looks as if pointers are just a complicated way of doing something we can already do by a simpler method. However, consider the following simple problem - write a
function which swaps the contents of two variables. That is, write swap(a,b) which will swaps over the contents of a and b. In principle this should be easy:


function swap(int a , int b);
{
int temp;
temp = a;
a = b;
b = temp;
}


the only complication being the need to use a third variable temp to hold the value of a while the value of b overwrites it. However, if you try this function you will find that it doesn't work.

You can use it - swap(a,b); - until you are blue in the face, but it just will not change the values stored in a and b back in the calling program. The reason is that all parameters in C are
passed by value. That is, when you use swap(a,b) function the values in a and b are passed into the function swap via the parameters and any changes that are made to the parameters do
not alter a and b back in the main program. The function swap does swap over the values in a and b within the function, but doesn't do so in the main program.

The solution to this very common problem is to pass not the values stored in the variables, but the addresses of the variables. The function can then use pointers to get at the values in the
variables in the main program and modify them. That is, the function should be:


function swap(int *a , int *b);
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}



Notice that now the two parameters a and b are pointers and the assignments that effect the swap have to use the dereference operator to make sure that it is the values of the variables

pointed at that are swapped. You should have no difficulty with:

temp = *a;

this just stores the value pointed at by a into temp. However,

*a = *b;

is a little more unusual in that it stores that value pointed at by b in place of the value pointed at by a. There is one final complication. When you use swap you have to remember to pass the
addresses of the variables that you want to swap. That is not:

swap(a,b)

but

swap(&a,&b)

The rule is that whenever you want to pass a variable so that the function can modify its contents you have to pass it as an address. Equally the function has to be ready to accept an address

and work with it. You can't take any old function and suddenly decide to pass it the address of a variable instead of its value. If you pass an address to a function that isn't expecting it the
result is usually disaster and the same is true if you fail to pass an address to a function that is expecting one.

For example, calling swap as swap(a,b) instead of swap(&a,&b) will result in two arbitrary areas of memory being swapped over, usually with the result that the entire system, not just

your program, crashes.

The need to pass an address to a function also explains the difference between the two I/O functions that we have been using since the beginning of this course. printf doesn't change the
values of its parameters so it is called as printf("%d",a) but scanf does, because it is an input function, and so it is called as scanf("%d",&a).


Pointers And Arrays:

In C there is a very close connection between pointers and arrays. In fact they are more or less one and the same thing! When you declare an array as:

int a[10];

you are in fact declaring a pointer a to the first element in the array. That is, a is exactly the same as &a[0]. The only difference between a and a pointer variable is that the array name is a
constant pointer - you cannot change the location it points at. When you write an expression such as a[i] this is converted into a pointer expression that gives the value of the appropriate
element. To be more precise, a[i] is exactly equivalent to *(a+i) i.e. the value pointed at by a + i . In the same way *(a+ 1) is the same as a[1] and so on.

Being able to add one to a pointer to get the next element of an array is a nice idea, but it does raise the question of what it means to add 'one' to a pointer. For example, in most
implementations an int takes two memory locations and a float takes four. So if you declare an int array and add one to a pointer to it, then in fact the pointer will move on by two
memory locations. However, if you declare a float array and add one to a pointer to it then the pointer has to move on by four memory locations. In other words, adding one to a pointer

moves it on by an amount of storage depending on the type it is a pointer to.

This is, of course, precisely why you have to declare the type that the pointer is to point at! Only by knowing that a is a pointer to int and b is a pointer to float can the compiler figure out
that

a + 1

means move the pointer on by two memory locations i.e. add 2, and

b + 1

means move the pointer on by four memory locations i.e. add 4. In practice you don't have to worry about how much storage a pointer's base type takes up. All you do need to remember is

that pointer arithmetic works in units of the data type that the pointer points at. Notice that you can even use ++ and -- with a pointer, but not with an array name because this is a constant
pointer and cannot be changed. So to summarise:

1.An array's name is a constant pointer to the first element in the array that is a==&a[0] and *a==a[0].
2.Array indexing is equivalent to pointer arithmetic - that is a+i=&a[i] and *(a+i)==a[i].

It is up to you whether you want to think about an array as an array or an area of storage associated with a constant pointer. The view of it as an array is the more sophisticated and the

further away from the underlying way that the machine works. The view as a pointer and pointer arithmetic is more primitive and closer to the hardware. In most cases the distinction is
irrelevant and purely a matter of taste.

One final point connected with both arrays and functions is that when you pass an entire array to a function then by default you pass a pointer. This allows you to write functions that
process entire arrays without having to pass every single value stored in the array - just a pointer to the first element. However, it also temps you to write some very strange code unless you

keep a clear head. Try the following - write a function that will fill an array with random values randdat(a,n) where a is the array and n is its size. Your first attempt might be something
like:


void randdat(int *pa , int n)
{
for (pa = 0 ; pa < pa =" rand()%n" i="0" pa =" rand()%n" i="0" or="" i="0">

23 March, 2007

Double your reading rate

Today, I have read an interesting article about how to speed up your reading.
Here is it. Enjoy!

Reading is an incredibly important skill to have. Just about any form of education will involve reading, sometimes almost exclusively. You can often make yourself an expert on an intellectual subject just by reading enough in that area. But despite the incredible importance of reading, most people are wildly inefficient at it. Like a child that never goes beyond a crawl, most people have enough reading skills to move around, but they are far from running.

Over a year ago I picked up the book, Breakthrough Rapid Reading by Peter Kump, an expert in the area of speed-reading. From that purchase I took the time and energy to study other ways to improve my reading skill. I recently got a chance to finish Eckhart Tolle's, The Power of Now, and I read the last half of the book in under forty minutes.

When I did the initial test at the start of the book, I could read at 450 words per minute. A little above the average of around 300, but nothing spectacular. By using the techniques I'll describe in this article I was able to increase that rate to around 900 words per minute in average situations, at least doubling of my reading rate.

I believe there are six major keys to improving your reading skill. Like all skills, success only comes through practice, so just reading this article won't be enough. But if you are interested in how you might be able to make dramatic improvements in both speed and comprehension, I've found these six points to be the best start.

1) Remember, Reading is Not Linear

How do you read a book? Likely from start to finish, never going back and never skipping any sections. This is probably one of the most inefficient ways to read. The beauty of text is that it is non-linear. You can skip down to read only my main bullet points, or read them in practically any order. Although the pattern of start to finish might be a simple one, it isn't always the most effective.

For most books I do read in a roughly start to finish fashion. But I frequently re-read passages that I want to get a greater understanding of and completely skim over passages that I feel are redundant or unnecessary. Good writers generally add anecdotes or metaphors to improve understanding of a concept which you can skim over top of if you already get their point. Similarly, bad writers often go short on explanation of complex details so re-reading can allow your brain the time to form the concepts.

Not only is reading non-linear but it doesn't have a set pace. Although I read some books at about 900 words per minute, I slow down to 200 if the passage I am reading is particularly information dense or complicated. Similarly I can skim at over 1500 words per minute if I'm reading mostly fluff. Saying I can read at 900 wpm is like saying I can drive at 100 km/h. Speed reading isn't just about faster but pacing yourself for the specific reading task you face.

Most people read a book as if it were given to them as a speech. They listen to the author and follow along with what he is saying in a purely sequential manner. In order to reach faster rates of comprehension you have to learn to abandon this tactic. You can start this by not subvocalizing.

2) Stop Subvocalizing

When you started to read you probably read out loud. Your elementary school teacher wanted you to read the book and say the words aloud. After you mastered this skill, you were told to simply say the words inside your head and read quietly. This is where most reading education and skill levels end.

To move to a new level you need to stop sounding the words inside your head or subvocalizing. Subvocalizing takes time, more time than is necessary to comprehend the words you are reading. It is almost impossible to go much beyond 400 or 500 words while subvocalizing. Instead you need to train yourself to read without hearing the words in your head.

But for most people this has become such an ingrained reading habit that they don't realize that subvocalization is a distinct process to comprehension. If I read at around a thousand words per minute, there is no way I could hear the words in my head while trying to process them. Instead I simply see the word and my brain automatically constructs what has been written. I'll understand a line of text that I looked over in a second, even though it may have taken at least five just to say the words in my head.

Since most people currently can't separate the subvocalization from comprehension, they are locked in at a rate of about 400-500 words. Moving beyond that rate requires that you practice reading faster than you can actually read.

3) Practice Reading

Practice reading doesn't mean reading. Practice reading involves reading faster than you can actually read. Chances are you won't comprehend much of what you are reading because your brain is so used to going at a slower rate and subvocalizing. The point is simply to see the text faster than you can read so you can untie the habit of sounding the words as you comprehend them.

You can start doing this by taking out a timer or a stop watch and simply viewing as much text in a book as possible in one minute. Use a book you haven't read before to ensure your brain is actually practicing instead of relying on memory. Mark out where you started and stopped. Count the number of words per line (use a quick average) and then the number of lines you actually read in the book to compute your practice reading rate.

Once you get used to practice reading at a high rate that you can't comprehend, you should slowly be able to actually comprehend at a slightly slower rate but still faster than if you subvocalized. I would often practice read at between 1500 and 1800 words per minute, and although I lacked comprehension skill, I could maintain it at about 900-1000, over double what I had done when I subvocalized.

But how can you practice read faster than you can read? How do you follow the text but still go faster than you can read? The answer is another of speed reading tricks, using a pointer.

4) Use a Pointer

Your eyes don't stay fixed in one spot when reading. Eye tracking movements have shown that your eyes actually quiver and move around considerably. And every movement away from your position in text requires a few milliseconds to readjust. These little readjustments in locating your place in a book add up to be very costly if you want to go faster.

Use your index finger to mark where you are on the page at all times. It should follow along with the word you are currently reading, slowly scrolling across each line and then back down one. It may feel awkward at first and it may even temporarily slow your reading rate as you adjust, but using a pointer is critical if you want to improve your reading skill.

Using a pointer is also crucial if you want to practice read. By moving your finger faster than you can actually read, your eyes get used to viewing text faster than your brain can process what is written down. This will break your subvocalization attachment and can easily let you double your reading rate with sufficient practice.

You should use your finger as a pointer all the time. When I first started with the habit I found it annoying to hold the book in a funny position so I could use my right hand to scroll the page. I thought it was silly and maybe even a waste of time. But now I find it hard to read without a pointer. Noticing how much it has helped me focus my reading efforts it is a priceless tool in reading.

5) Eliminate Distractions

As a university student living on campus I've noticed a few of my friends who "study" while watching television. Not surprisingly, these tend to be the same people who complain about how much studying they have to do. Reading can't happen in an environment where external distractions are overwhelming.

If you need a break, take a break. Taking a few minutes to watch a television show, listen to some music or just close your eyes can often improve your focus. But don't multitask with your reading or you'll lose any benefits speed reading can offer. Worse, because you have stopped subvocalizing, you might even skim through several pages before you realize you haven't comprehended anything that was written.

Distractions will hamper regular reading but they will make speed reading impossible. Subvocalization creates enough mental noise that it can hold your attention, but without that it can often be difficult to stick with what you are reading.

External distractions may be a problem, but internal distractions are just as bad. They occur when in the midst of reading you start pondering that conversation you just had with a friend, the movie you want to see or whether you should do your laundry. The way to remove internal distractions comes from clearly identifying a purpose and a motivation.

6) Find Your Motivation

If there was one piece of advice I would offer to improve your reading rate it would be simply to engross yourself in the material you are studying. If you can connect what you are reading to a deeply held motivation, and determine your specific purpose for reading you can maintain a very alert and focused state.

Most people don't do this. Instead they force themselves to study the book they know they should and end up having to refocus themselves every thirty seconds when their mind decides that this book is boring and would like to be somewhere else.

First, find a general motivation. This is how what you are reading relates to your truly motivating goals and passions in life. When I read my psychology textbook I focus on the fact that many personal development principles come from an understanding of human psychology and that I may discover new ideas if I look carefully. When studying ancient Asian history I focused on the fact that studying a completely different culture could offer insights into how Western and Eastern value systems differed, giving me new thoughts on whether my values are as absolute as I once thought. I also focused on the fact that many great philosophers such as Buddha and Confucius lived during these times with a profound influence on the ideas of these nations.

The general motivation should make you want to read the book. If you don't genuinely want to read the book, come up with more reasons it is attached to your deepest interests or it is going to be a struggle to move through. You can find a general motivation for reading any book if you are creative enough, so don't tell me you can't figure out one.

The second portion is to determine your specific motivation for reading. What are you specifically looking for when reading the book. New ideas? A practical solution to a problem? An understanding of a concept? A chance to flex your mental muscles? Figure out what you want to get out of each reading session so your mind is primed to intake that knowledge.

If you are interested in improving your speed reading, I strongly suggest Breakthrough Rapid Reading by Peter Kump. The book goes from beginner concepts that I've detailed to even more advanced ones that I have yet to master (such as reading several lines at once and reading sentences backwards to save time on a pointer backstroke). Speed reading is definitely a worthwhile skill and at the very least your friends will be impressed.

Link