Search
Left Quote    Wise men speak because they have something to say; Fools because they have to say something.
- Plato (427-347 B.C.)    
Right Quote
 
[login] | [Register]
 

C Tutorial

by: Jester
Page: 6 of 10
(View All)

Pointers and Arrays


Arrays and pointers are closely linked in C. To use arrays effectively it's a good idea to know how to use pointers with them. Let's have a look at an example:


Compile this program and run it.

It won't run, why? Because you can't assign a to b. You have to use something like this:


The line #define MAX 10 is a simple constant. We haven't seen this before so i should mention it. All it is in a CONSTANT value we can use throughout the program. MAX is a variable that holds the value of 10, only we cannot modify it, it's constant. Constants are normally typed in upper-case to make it obvious to anyone reading the program that it is a constant.

a and b are unusual in C in that they're not techinically arrays themselves. They are permanent pointers. What does that mean? Well, a POINTS to the first item in its array, and b POINTS to the first item in it's array, they are pointers, only they cannot be changed to point to something else. They hold the addresses of a[0] and b[0]. Therefore a = b; is illegal.


The code above is legal. p = a; works because a is techically a pointer, so assigning a to p makes p contain the address of the first element of of the array a[]. So now *p points to a.


Remember, a is a pointer, it points to address of the first element in the array, and always points there. &a[0]; is the address of the same item in the array, so they are the same.

Now that we have assigned the address of a[]'s first element to p, we can use the pointer to move around the array, consider the below:


This will output:

pointer is pointing to the value 5
pointer is now pointing to the value 7

Do you see? We can use the pointer to jump through the array elements. If we increment p then the pointer will jump the appropriate number of bytes to the next array item. C takes care of the issue of element size, so adding one will jump to the next element, adding two will jump to the element after the next element... etc.



1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |  9  |  10  |  
Next »


No Comments for this page.

You Must be logged in or a member to comment.


Tutorial Stats

Tutorial Stats

27,396 Views
0 Total Comments
3.33 Rating of 5 (3 Votes)

Options

Tutorial Options

· Login to Rate This Article
· Login to Post a Comment
· Read more by this author
Digg This Article! Del.icio.us: Bookmark This Article Reddit: Bookmark This Article BlinkList: Blink This Article! YahooMyWeb BlogMarks: Add This Mark! Furl: Save This Article Spurl: Mark This Article

Articles

Related    

· Beginning Visual C++ 6.0
Your Article Here



"AllSyntax.com" Copyright © 2002-2018; All rights lefted, all lefts righted.
Privacy Policy  |  Internet Rank