Solved

arrays and pointers

Posted on 2000-04-24
9
403 Views
Last Modified: 2010-04-16
Im doing a course in Pascal and dont understand the concept of array and why you use pointers can anyone help me on this easy subject?

Thanks in advance Lee
0
Comment
Question by:helee
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 1

Expert Comment

by:nrico
ID: 2744797
First of all, pointers is not an easy subject. I too found it difficult to understand when I learned about them.
But as you'll practice more, you get used to them :-).

An array is effectively any number of the same variable types, also stored next to each other in memory. You can have an array of 300 bytes, 50 strings or 6000 records, just what you want. The array can consist of any possible Pascal type.
All these members can be accessed using their "index", or their position within the array. Probably, you'll refer to the first item as 1, the second as 2, etc, but you can give them any numbers you want.
When you declare the array, you specify what type the array consists of, and how large it is. Ex:

  MyArray:Array[1..300] Of Byte;

would create a 300-byte memory block, in which you can access the separate bytes using this construct:

  WriteLn(MyArray[50]);

would print the 50th byte out to screen. You can in this way also assign values to it. You can use the array member as any other variable.
Arrays are useful if you have to work with high number of similar data.
Say you have ten numbers, and you want to know the sum of these numbers.

You might do something like this:

Var
  Num1,Num2,Num3,Num4,Num5,Num6,Num7,Num8,Num9,Num10:Integer;

Function ReturnTotal:Integer;
Begin
  ReturnTotal:=Num1+Num2+Num3+Num4+Num5+Num6+Num7+Num8+Num9+Num10;
End;

Now, if you put the number in an array, it could look like this:

Var
  Numbers:Array[1..10] Of Integer;

Function ReturnTotal:Integer;
Var
  Counter,SubTotal:Integer;
Begin
  SubTotal:=0;
  For Counter:=1 To 10 Do
    Inc(SubTotal,Numbers[Counter]);
  ReturnTotal:=SubTotal;
End;

This results in much "cleaner" code, and it can easily be expanded to 20 or even 100 numbers, whereas in the first example you'd have to rewrite *MUCH* code.

About pointers:
This is a bit more difficult to understand, but I'll do my best.

A Pointer is basically a variable that "points" to a certain memory location. The pointer may expect a variable of a certain type at that location, in which case it's called a "typed pointer", or it just doesn't care, and then it's an untyped pointer.
You declare them both differently.
A typed pointer is declared by putting a "^" (I believe it's called a hyphen, but I'm not sure about that) in fron of the type you want to point to.
Say I want a pointer to a byte. I'd declare it this way:

  MyPointer:^Byte;

Now MyPointer will always expect it's pointing to a byte; I will show you later how to access this byte.
First, we want to make sure the pointer is pointing to a location in memory that we can so something with. At the beginning of the program, MyPointer's value would obviously be illegal and writing to it would most probably crash your computer.
To reserve memory for the pointer, we call
 
  New(MyPointer);

MyPointer will now point to a location in memory where 1 byte has been reserved for you to do something with.
You access this byte by now putting the hyphen AFTER the pointer's name, like this:
 
  MyPointer^:=25;

The byte pointed to by MyPointer will now contain the value 25. THE VALUE OF MYPOINTER ITSELF HAS NOT CHANGED. It still points to the same location in your memory. To change the value of MyPointer itself, remove the hyphen, but that would be inadvisable since you wouldn't be able to access the original byte anymore.
To release the memory associated with MyPointer, call
 
  Dispose(MyPointer):

The byte is now released.

An untyped pointer works similarly, but now you also need to tell the computer _how much_ space to reserve for the pointer, because it can't determine that from the type (It doesn't have a type, remember?).
An untyped pointer is declared this way:

  MyUntypedPointer:Pointer;

Just plain "Pointer".
You reserve memory for it with
 
  GetMem(MyUntypedPointer,300);

This reserves 300 bytes for MyUntypedPointer.
You release the memory with

  FreeMem(MyUntypedPointer,300);

MAKE SURE YOU USE THE SAME NUMBER BOTH TIMES!

You access this memory in the same way (MyUntypedPointer^), but you cannot simply assign a value to it, because it doesn't have a type.
You'll have to use typecasting for that, but that's another complicated issue and not in the topic of this Q.

Ooooookay -- that's about it I believe. Ask me if anything's still not clear.
0
 
LVL 3

Expert Comment

by:Mathias
ID: 2744814
An array is a list with a predefined number of values, for example

var abc: array[1..3] of Byte;

Now you have three elements. I you want elements 3 then you would write

writeln(abc[3])

PS: This variables have already their memory addresses.

If you have pointers your program is smaller because the variables get their memory and addressed in their runtime. If you want to use those pointers, you have allocate/deallocate memory.

var abc: array[1..3] of ^Byte;
{^Byte = ^ stands for pointer}

var b: byte;
begin
  for b:=1 to 3 do
  begin
    {allocate new memory}
    New(abc[b]);
    {do something with it}
    abc[b]^:=b;
  end;
  {write the values}
  for b:=1 to 3 do
    writeln('Value of abc[',b,']^: ',abc[b]^);
  {dispose the allocated memory}
  for b:=1 to 3 do
    Dispose(abc[b]);
end.

I hope you can follow the example.

Bye, TDS.
0
 
LVL 1

Expert Comment

by:nrico
ID: 2745150
I must point out, TDS, that this example is quite useless.
Your replacing a Byte (1 byte) with a Pointer (4 bytes)...

But I get your point :-)
0
 
LVL 1

Expert Comment

by:nrico
ID: 2745159
Hey TDS, is there any place I can get a look at your Doors? (What's in a name! Shouldn't this have been Linux's? ;-)
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 3

Expert Comment

by:Mathias
ID: 2745296
nrico

Give me the email address where I can send the test executables for the hardware detection (ca. 270KB).

The GUI and the mouse driver aren't ready for publishing. The basic OS based on RxDOS and PTS DOS.

If you want some code, there is a way to exchange some sources.

Bye, TDS.
0
 

Accepted Solution

by:
Ozzy_98 earned 50 total points
ID: 2750071
Arrays and Pointers are two of the most usefull things any programer can use. They might be scarry at first, but after using them awhile, they just "click" in, and you'll have no problem using them.
 An array is a bunch of varriable hooked together.  Say you are making a game.  You have five players, and need to keep track of all their hit points.  Without an arrray, you would need 5 variables.  With one, it's much easier.  Instead of HP1, HP2, HP3...ect. you have HP[1].  But, the most usefull powers of arrays are using multi-layerd arrays and using them in loops.
 Say you want to print the hit points out.  With an array, it would be like this:
 for loop := 1 to 5 do writeln (HP[loop]);
 Using one line, you did what would have been five. And you only have to remember one variable, not five.
 But the best part of arrays are multi-layered.  I think of an array as a line on a sheet of graph paper.  Each block can store on int, char, or even string.  A multi-layered array is like the sheet of graph paper.  You now have line at the top, and for each number there has the row below it. Think of them as x and y coordinates to help make it easier.  So, in you game, you need to keep track of the hit points, magic points, and money of each player.  The first number in the array, x, is the number of the player. The second refers to which stat you need, HP, MP, or Gold. So, to show the Mp of player 3, it's: Writeln (Player[3,2]);, player being you array, and 2 being the magic.   If you need a three-layered array, think of it a multi-sheets of graph paper. You can set the Mp to have current, and max.  If current is page one, and max is page two, to show the current mp would be like this:
  Writeln (Player[3,2,1]);
Write down how you have your array set up, ie. what variable is where, and you should have no problem.  Do any more then three, and you better have a good understanding of arrays, or you'll get lost. :) Just remamber, think you it as a grid. Visualizing helps out lots in programing.
  As for pointers, first rule: WATCH OUT FOR TYPO'S!!!!  I've locked up my computer many a time becouse I miss typed my pointer.  
  Pointers are like variables, vary close to variables, even.  There is little you can't do with pointers that you can't do with variablres, but pointers are easier for many things.
  A pointer does just that: points.  Most of the time, you use it to point to an area of memory, and use the pointer like a variable.  You tell the computer to store something into the memory, using the mem command, or getimage, or what ever.  Then using the pointer, it goes to the variable, or image.  If you use the getimage command (in the graphics unit, it save a rectange-shaped area of the screen into memory.  Draw a nice picture, and this will save it into memory. You and also use it to move the picture around, like a sprite. See you help file for more.), it saves the image into memory.  You now can do what ever you want by using the pointer.  Putimage will put it onto the screen, and with blockwrite, you can save the image into a file, and load it up anytime, without having to re-draw it.  That helps to speed thing up a bit.
Since you are taking a course about this, I'll bet your using pointers with data-files.  This can be tricky, I never got it until after I was done with my schooling.  It works exactly the same as using a pointer in memory, it points to a place in a data file, so you can start up where you left off.  However, most of the time, this practice is ill-advised.  If the file is large, use a pointer. If not, i would read everything into an array, or multi-layered array.  This way, you only have to read the data file one time, and if you do this when the user will not notice it, like between levels in a game, they'll never see you loading.  And you can access the data any time now, instead of reading it off a file every time you need it.  The pointer in this case is just a book mark.
 But, your thinking, what the heck is a pointer good for?  I can use variables to store stuff like that.
  Well, in intery-level stuff, like in school, not much.  Using it as a bookmark is nick, that's it.  But as i said, it's one of the most powerful items a programer can learn.  If you start using higher-end graphics (read about "mode x" of examples), this is very useful.  If you draw an item on the screen, it'll flicker as you draw it.  So, you set up an area of memory the same size of the screen, and draw on that.  (This is a simplistic view, as there is not pre-made procedures to draw onto an area of memory) Then using the move command, you move that area of memory into you video memory. (Anything the tells you about mode x will explane this)  This is a lot faster then drawing straight to the screen, and stops the flicker. The pointer is what tells the computer where this virtual screen is, so it can copy it onto the real screen. It's basicly the variable name for that memory address.
 But as I said, watch for typos. You probley have the code that tells you how to declare the pointer, or you can use the help menu, or read the other answers give.  
Just remember when to use the ^ (called a carrot, a hyphen is -, same as a minus symble. :) )Remember, you messing with the computer's memory now. If you tell it to write into the wrong spot, (try not using the carrot once, you'll see) and you could write over anything.  However, following my experince, you'll write over dos.  This means you'll not be able to do anything, and your computer will lock up.  Can you say reboot?  Always save before you try anything changer using a pointer.  As for declaring them, there is a good example in the getimage/putimage in the help menu of pascal, or use the way nrico or TDS have in their examples.  (I know, it's hard to read somelse's code, but the help menu has a good example for this one, it's simple, and you see how to use it.)
 As for using multi-layered arrays, you'll not find anything good about that, too simple for the experts, so they skip over it, or just can't explane it so new programes can understand it.  Heres how you declare my player example:
 player : array [1..5] of array [1..3] of array [1..2] of integer;

The first array, the top of your graph paper, is the players.  Array two, the rows going down the page, are the stats: HP,MP, Gold.  Array three is the diffrent pages of graph paper.  They show the current number on page one, and the max on page two.  All in one easy variable.  And best of all, you can use it in a loop.  And if you didn't know, a string is an array of char's.  You can basicly use it like any other array.  

  Need any thing explaned, e-mail me. (it's Ozzy_98@msn.com, if you don't feel like looking it up.)
P.S. Sorry about and spelling miskates. I am a reealy bad speller. :)
0
 

Expert Comment

by:Ozzy_98
ID: 2771434
Ozzy_98 changed the proposed answer to a comment
0
 

Expert Comment

by:Ozzy_98
ID: 2771441
Is helee still alive? Must not have needed that answered to soon.  (Hope I get these points, I've got lots of questions to ask )
0
 

Author Comment

by:helee
ID: 2772507
Sorry for the delay its been hectic as there have been two holiday weekends in a row here in England. I hope you can ask your questions now Ozzy

Sorry

Lee
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Owning a franchise can be the dream of a lifetime. It provides a chance for economic growth. You can be as successful as you want.  To make your franchise successful, you need to market it successfully. Here are six of the best marketing strategies …
What is Backup? Backup software creates one or more copies of the data on your digital devices in case your original data is lost or damaged. Different backup solutions protect different kinds of data and different combinations of devices. For e…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now