?
Solved

Another beginner question... this time it's about pointers.

Posted on 2003-03-23
12
Medium Priority
?
273 Views
Last Modified: 2010-04-04
Okay I have a general question here. I understand that pointers are simply something that points to an object in memory. I just don't understand when exactly I would impliment them, or what the pros-cons are to them. I read somewhere that you don't really need to use pointers in delphi anymore, but I always see them when i am looking at code samples.

I guess my question is, When should i consider using pointers?... pointers are scary!

Best Regards,
Steve
0
Comment
Question by:PoeticAudio
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
12 Comments
 
LVL 1

Expert Comment

by:Maximilianop
ID: 8192377
Well the fact as I know is like this:
  As you said pointers are just "things" that point to the object's memory address (or should I say, object's entry point on memory?) since, in Object Oriented Programming, The name of the object is like a pointer to it's memory, you don't really have a need for them but when you want to make some lower level operations, like for example know the size in memory of the object, or when you want to read specific bytes on it's allocated memory.

  Once again, pointer's are not really needed, but some "compiler" functions asks for an object's pointer.

  Other times when you want to use object's pointers are for accesing the data of the objects without having the problems of class incompatibility.

  Well further info should be told by other people with more expertise on the area.
0
 
LVL 3

Expert Comment

by:emadat
ID: 8192763
What a big question...

I do not think that one can address such a big issue in a simple answer.

Let me give it a try. A pointer is a data type which holds a memory address. This address can be the address of an object, a function, a procedure or of anothr data type.

Most of Windows API functions requires their parameters as pointers to some data structures.

Some of the API calls require pointers to one of your local functions to "call you back" at that function when they do something for you; like the enumeration functions.

You are also using pointers in your code most of the time.
For example; when you use the "var" key word in the declaration of the parameters list of a function or a procedure; you are telling Delphi to send a pointer to that variable not the variable itself. The called function then works on the original copy of the variable.

Also if at one point of time you decided that you need to go low level and write assembly code in your Delphi app; you will need to deal with pointers.

Pointers are not scarry once you know how to deal with them.

Here are a couple of articles that can help you understand them more.

http://delphi.about.com/library/weekly/aa011601a.htm
http://www.sddug.slctnet.com/pres_e.htm

I hopt that helps.
Regards,
0
 
LVL 6

Author Comment

by:PoeticAudio
ID: 8193134
Well, thanks to both of you for the useful info, I am now confident that I know what a pointer is, i'm just not sure when I should consider using a pointer variable. Emadat you said that everything we declare is actually a pointer. That confuses me a little bit because why would I ever need to actually declare a pointer like...

Var
  MyPtr: ^Integer;

or even

Var
  MyPtr: ^MyClass;

what would the difference be between that and just doing
MyInt: Integer; or MyClass: MyClass; without referencing it to a pointer? Maybe I should increase the point value to this question because I didn't realize how vague it actually was. But again I thank you guys for the help.

Best Regards,
Steve
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 6

Expert Comment

by:edey
ID: 8193340
the (main) difference in the above example is code size. Lets say we wanted an array of a million chars. Declaring such an array would make our compiled code size a mb bigger (a million x 1char) versus 4 bytes (1 x 32byte integer/memory address). The memory usage is (nearly) the same, but the file sizes differ greatly.

GL
Mike
0
 

Accepted Solution

by:
BLayman earned 200 total points
ID: 8193395
Well, the simple fact of the matter is that you use pointers all the time.  Delphi just hides it all from you.  Nice, huh!

Any time you assign an object to a property:
   Form1.ActiveControl := Edit1;
Hey, you just used a pointer!!!

And now watch this:
   function Return25: Integer;
   var
     MyInt: Integer
   begin
     MyInt := 25;
     Result := MyInt;
   end;
Oops, you did it a few more times!  You created a pointer to an piece of memory the size of a long integer, allocated the memory, dereferenced the pointer and put the value in that spot in memory, and when you reached the end of the method, you release the memory back into the memory pool.

Delphi takes the references to the objects and variables that you are using figures out what you want to do as it compiles.  Then it does all the work.  It decides if you wanted to assign the address of the object you referenced (:= @Edit1) or if you want to get at the value of the data in that address (MyInt^).

So, don't worry.  You can do most of anything you want to do in Delphi without resorting to pointers.  If you are new to Delphi use TLists and TStringLists a lot and you can avoid actual pointers for a long time.

Now that being said pointers do have their time and place.  That's another nice thing about Delphi.  Many high level languages hide pointer usage (VB is King in this area).  However Delphi also lets us use them when we need to.  VB, unless .net changes this, doesn't.  

So as emadat says if you try to do things at a lower level, using API calls - the basic building blocks of Windows itself, you will have to manually control many of the pointers.  Even then Delphi hides many of the rigors that would be involved in making api calls in language like C.  Here's a simple program, all from the DPR, that sets the resolution of a monitor:
program ResetRes86;

uses
  Forms,
  Windows;

{$R *.RES}

var
  pDMode : _DEVICEMODEA;
begin
  Application.Initialize;
  pDMode.dmDisplayFrequency := 75;
  pDMode.dmPelsWidth        := 800;
  pDMode.dmPelsHeight       := 600;
  PDMode.DmFields := (DM_PELSWIDTH or DM_PELSHEIGHT or DM_DISPLAYFREQUENCY);
  pDMode.dmSize := SizeOf(pDMode);
  ChangeDisplaySettings(pDMode, CDS_UPDATEREGISTRY);
end.

You can see that I've used a pointer to a Device mode structure.  However that structure is being created by Delphi and not by the API call "ChangeDisplaySettings".  So Delphi handles all of the allocation, deallocation and dereferencing for me.

However, at my office we have a program that passes a Enhanced Metafile from one computer to another using a Windows message.  We have to use pointer in order to access the memory directly and do what we need to do.  Delphi has no direct handling for that as it is not something commonly done.  So our code looks something like this (this snip is actually from the Delphi source directory but it is the same idea.  I don't have our real code here.)
var
  WMF: TMetafileHeader;
{---->}  BitMem: Pointer;
  MFP: TMetaFilePict;
  EMFHeader: TEnhMetaheader;
begin
  NewImage;
  Stream.Read(WMF, SizeOf(WMF));
  if (WMF.Key <> WMFKEY) or (ComputeAldusChecksum(WMF) <> WMF.CheckSum) then
    InvalidMetafile;
  Dec(Length, SizeOf(WMF));
{---->}  GetMem(Bitmem, Length);
  try
{---->}    Stream.Read(BitMem^, Length);
....
  finally
    Freemem(BitMem, Length);
  end;

As you can see we create the pointer.  At that point it is just like an empty change-of-address form waiting for you to fill in the address.  We then grab a chunk of memory the size that we want and make the pointer point to it. (We build the house and fill in the change of address form.)  Then we read our information from the stream into the chunk of memory we grabbed.  (Or we fill the house with furniture - Hey this is a great analogy!) Finally, we free up the memory since we don't need it any more. ( We blow up the house for insurance- Ok, so the analogy breaks down here...it was fun while it lasted.)  
(Also notice that we put the try AFTER we've successfully allocated the memory - a common newbie mistake is to put it before. sorry had to get that in)

So,  I hope this made it a little clearer for you.  In short you'll directly use pointers so infrequently that along with every other Delphi user, every time you do it will take you three tries to remember whether to use @var, ^var or var^.  That's what I have to do too! <G>

 
0
 

Expert Comment

by:BLayman
ID: 8193462
BTW I don't think I agree that there's a huge memory saving.  Delphi has many different data types built into it.  You can define variables of any just about byte length.  Since Delphi's structure point directly to the memory, you can get things to be very small without referencing pointers.  And it is not the compiled size that would differ in any case,  you would simply use more memory as you are running the program.  And what's a meg or two between friends anyway right?  I'm quite certain that edey can come up with an examples that takes up more memory but I bet I could come back with another way that would be just about as effecient.

You'll get your first taste of pointers, I expect, working with arrays of PChars.  These are essentially the old way of handling strings.  And it is probably what edey is referring to.  PChars are also how windows handles strings natively.  So they are seen more often and in the most common of the API.  

Delphi provides all the conversion routines that you need to work with the strings.  You come to think of them not as pointers but as a different string datatype.  You'll just wrap your string variable in PChar() and be done with it or use StrCopy to move the data back to Pascal strings.  Any small loss of memory in using Strings and TLists vs PChar arrays and linked-lists are far outweighed but the fact that the code is simple enough that it will run the first time you try it.  It is only when you start to do fancy stuff like writing graphically intensive arcade games that these differences really start to stand out.  But since Delphi handles both methods well, you're still made in the shade.
0
 
LVL 6

Author Comment

by:PoeticAudio
ID: 8193486
Well, thanks to both of you for the useful info, I am now confident that I know what a pointer is, i'm just not sure when I should consider using a pointer variable. Emadat you said that everything we declare is actually a pointer. That confuses me a little bit because why would I ever need to actually declare a pointer like...

Var
  MyPtr: ^Integer;

or even

Var
  MyPtr: ^MyClass;

what would the difference be between that and just doing
MyInt: Integer; or MyClass: MyClass; without referencing it to a pointer? Maybe I should increase the point value to this question because I didn't realize how vague it actually was. But again I thank you guys for the help.

Best Regards,
Steve
0
 
LVL 6

Author Comment

by:PoeticAudio
ID: 8193488
Sorry didnt mean to post that again...
0
 
LVL 6

Author Comment

by:PoeticAudio
ID: 8193603
Well, again I must express my great thanks to you guys for helping me out on this topic so much. A special thanks goes out to BLaymen for that analogy. I will now look at pointers in a whole new (and less scary) way! You have all been a great help. I now realize how much work Delphi actually does for me(well probably not.. i'm sure Delphi does a GREAT deal of work)... Thanks Borland! =)

Best Regards,
Steve
0
 

Expert Comment

by:BLayman
ID: 8193752
Just don't literally blow up any houses OK?

Hey-Do I get my first accepted answer credit with a grade and everything now?
0
 
LVL 6

Author Comment

by:PoeticAudio
ID: 8193776
Yeah you get it all buddy, i'm a little slow right now... kinda at work... agh.. night shift ::bleh::

Sorry about the belated points but here they come...

Regards,
Steve
0
 

Expert Comment

by:BLayman
ID: 8194099
Glad to be of service!  Thanks!
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The uses clause is one of those things that just tends to grow and grow. Most of the time this is in the main form, as it's from this form that all others are called. If you have a big application (including many forms), the uses clause in the in…
Hello everybody This Article will show you how to validate number with TEdit control, What's the TEdit control? TEdit is a standard Windows edit control on a form, it allows to user to write, read and copy/paste single line of text. Usua…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Suggested Courses
Course of the Month9 days, 19 hours left to enroll

762 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