article

A look at Arrays and Pointers

Email
Submitted on: 1/4/2015 3:12:00 AM
By: Abdel Jabbar Baig (from psc cd)  
Level: Beginner
User Rating: By 8 Users
Compatibility: C, C++ (general), Microsoft Visual C++, Borland C++, UNIX C++
Views: 816
 
     This is simply a tutorial that will teach you the basics of arrays and, especially, pointers. Additionally, it'll also show you how arrays and pointers are related to each other.

 
				Purpose
The purpose of this tutorial is to show you some relationship(s) between an array and a pointer. I have read some tutorials on C/C++ and the only thing they talk about is what pointers are and what they are used for. They don’t provide any insight about how they are related to arrays. If you know that then it’ll becomes a little easier for you to use pointers in your application. Starting up...
First off, your computer memory is divided into a bunch of “boxes” and each “box” has a size of 1 byte. You must know about, at least, the basic model of memory in order to use or understand pointers. Yes! It’ll make your learning curve easier! Let’s first look at a simple variable...
int x;
In the above line, we are declaring a variable called x which is of an integer type. A computer must somehow store this variable in order to use it in the future. So it stores this variable in the memory. But where? This type of simple variable is stored somewhere in your program’s memory space. An integer has a size of 4 bytes so it’ll occupy 4 “boxes” of your memory. Nothing else can use this memory space because it holds your variable unless your program exists. Yes! You can’t “empty” this memory space after you have put your variable x in there. A memory model containing x would like this:
| | | | |
Right now there’s nothing in those 4 “boxes” but as you assign some number to x, some or all of these boxes will be filled up according to the size of your number.
x = 4;
Now you have assigned a value of 4 to x. You can retrieve the value by writing x like this:
cout< So we can conclude that a value is some sort of data that is held in the memory space reserved for your variable.
[You:]Hmmm...ya, but the title of this tutorial says that you’ll tell about arrays and pointers so why just a variable?
I started with a variable to just show you what a variable contains a value and how it’s organized in the memory. Now we’ll talk about a simple array....
int x[4];
The above line declares an array of 4 integer. How much memory do you think is reserved for this variable (for now)? It’s not 4 bytes but 16 bytes! I am pretty sure you know about this.;) Now at the same time I’ll start talking about pointers...
A pointer is a variable, as usual, but it’s VALUE is an address of some other variable. You declare a pointer with prefix of * like this:
int *p;
Now if we want to access the value of p, we simply use the name “p”. But as I said before, the pointer’s value will holds some memory address. It is usually the address of another variable but not always! Try this first:
int x; //Declare a variable
int *p; //Declare a pointer
p = &x; //p now holds the memory address of x
cout<

You use the “&” symbol to access the memory address of a variable - NOT THE VALUE! The above code will print a hexadecimal address of x. See! The actual value of our pointer p holds an address. Now try this:
int x = 3; //Declare a variable
int *p; //Declare a pointer
p = &x; //p now holds the memory address of x
cout<<*p;

This one will print the actual value of x. But we didn’t really use the variable x to get the value. Because p already holds the address of x, you can use the prefix * to retrieve whatever is on the address that p holds. When we used ,*p, it actually looks at the value of p. The value of p is actually an address of some place in the memory so *p returns the value on that address. I guess now you’re pretty much set with a simple pointer.
Now lets get on our way to the original topic... Oh forgot to tell you another thing about a pointer. A pointer has 3 “things” compared to a variable which only has 2 “things”. A variable has a value and an address where a pointer has a value (address of some variable), its own memory address (we can get it using &p), and a pointed value which it gets by looking at its value (again, the memory address of another variable). We get the value using *p as I wrote above.
Let’s declare an array now:
int x[4];
It’s 16 bytes long in memory. The start of this array is x[0] so we can get the starting address of this array by using &x[0] (remember you use the “&” sign to get the address of a variable). Now remember this equation for an array (x is an array in this example):
x = &x[0];
Try it yourself and you’ll see the above equation is true! So if we have an array x, we can simply use x to retrieve the starting address of the array in the memory. We can now simply declare a pointer that points to the start of the array thus the value of our pointer will be the starting address of the array in the memory.
int x[4] = {1,2,3,4};
int *p;
p = x;
cout<<&x[0]< cout<

You’ll see that both line of outputs will be same. Why? Because, as I said before that x = &x[0], so
p = x ~ p = &x[0];
(~ means “is same as”)
We are just assigning an address to p which is completely legal.:) Now try outputting the value of *p. You’ll see “1" which is exactly the value of first item in our array! You can also increase the value of the pointer so that it points to next integer in the array. It’ll simply look at the type of the pointer. Because we declared it as an integer, it’ll increase the value of the pointer by 4 bytes (it’ll add 4 bytes to the memory address). Let’s try it:
#include
void main()
{
int x[4] = {1,2,3,4};
int *p = x;
for(int i=0;i<4;i++)
{
cout<<*p< p++;
}
}

The output will look this:
1
2
3
4

Exactly what we expected! The statement p++ is completely legal. It increases the value of p by 4 bytes so that its address is now pointing to the next item in the array. You’ll get the same output as above by using the following code:
#include
void main()
{
int x[4] = {1,2,3,4};
int *p;
for(int i=0;i<4;i++)
{
p = &x[i];
cout<<*p< }
}

We are using p=&x[i] to point to the next element in the array. Very similar (in this case same) to p++ (which is same as p=p+1 in case you’re wondering).
Dynamic Memory Allocation
Now we shall look at how you dynamically allocate memory. It’s very useful to use pointers instead of using A LOT of variables (especially of large types like double). As I said before that the memory of a simple variable is never freed unless your program ends. But you can ask the operating system to reserve a certain amount of memory for you at runtime and then you can free the memory whenever needed. You use pointers and some functions to do this job. We’ll use malloc() to allocate a certain amount of memory and then we’ll use free() to free this memory so the operating system or our own program can use it for other purposes. Here is an example of allocating memory:
int p = (int*)malloc(4); //Make sure you include
Because malloc() returns a void pointer, we have to cast it as an integer pointer. As you can see that malloc() only takes a parameter that tells the size of the memory to allocate (in bytes). In this case, we’re only allocating 4 bytes so we have allocated memory for only 1 integer (remember that 1 integer is 4 bytes). In this case, we have actually created an array that can only have one element (1 integer). Try this yourself:
#include
#include
void main()
{
int *p = (int*)malloc(4);
*p = 5;
cout<<*p< free(p); //Always do this after the allocation!!!!!
}

The output of the above code will be 5.
We allocated 4 bytes (1 integer) and then we set it to 5...you’ll see something amazing in a moment! Now try this code:
#include
#include
void main()
{
int *p = (int*)malloc(4);
p[0] = 5;
cout< free(p);
}

Same output! As I said before that we have actually created an array that can have one element. You should also recall that simple equation for an array:
p = &p[0];
So we can also say this:
*p = *(&p[0]);
Exactly same! If you look closely at the above two complete examples, we are simply following these equations. Now let’s do something with more than 1 element:
#include
#include
void main()
{
int *p = (int*)malloc(8);
*p = 5;
cout<<*p< p++;
*p = 6;
cout<<*p< p--; //We have to return back to the start of the array or free() will give an error!
free(p); //Always do this after the allocation!!!!!
}

The out will be
5
6
We simply allocated 8 bytes (2 integers) and then we assigned 5 to the first element of the array (look up the above 2 equations I wrote). Then we increased the value of p so that it adds 4 more bytes to the memory address that it’s holding thus it holds the next element in the array. I had to use p- - or it’ll give you an error when freeing the memory. I think it wants us the make the pointer hold the starting address of the array? Guess so! This following code will give the same output as above:
#include
#include
void main()
{
int *p = (int*)malloc(8);
p[0] = 5;
p[1] = 6;
cout< cout< free(p); //Always do this after the allocation!!!!!
}

Again, we are just using the pointer as an array. We don’t have to increase its value so that it points to next memory address, next one, next one, and so on.
NOTE: Statements like “int *p = (int*)malloc(3);” will crash your program because you’re only allocating 3 bytes but an integer requires a minimum of 4 bytes in order to be created!

Conclusion...
I guess by now you should have a basic understanding of what pointers are and how they’re related to arrays. Happy “pointers” and “arrays”!:D
Please post any errors in the feedback section if there are any in this tutorial. Comments, suggestions, and improvements are welcome.:)


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.