Lazarus

Programming => General => Topic started by: captian jaster on May 03, 2010, 08:49:24 pm

Title: Can someone please explain pointers..
Post by: captian jaster on May 03, 2010, 08:49:24 pm
Do they hold data stored in another variable or what? cuz i dont get it.
Title: Re: Can someone please explain pointers..
Post by: Martin_fr on May 03, 2010, 09:25:24 pm
All you variables must be stored somewhere in the memory of your computer.

From the point of your application, that can be  for example on the stack, or the heap (but both are part of the overall memory of your computer)

Each place in the memory has an address. So each variable you have is located at some address.

A Pointer stores the address of another variable. It does not store the data of this variable, only where in the memory it can be found.

var
  a: Integer;
  pa: ^Integer; //Pinteger / pointer to integer

pa := @a;

pa contains the address of "a" in memory.

But if "a" moves to another address, or is entirely removed (yes it can happen), then pa doesn't know that. pa still has the address where "a" used to be.
if you do access this address, you may cause an error. (an immediate error, or an error at any later time)

As long as "a" is still in place:
pa^

returns the data which is stored in "a"

"^" is the dereference operator. It means you are not interested in the address stored in pa, but in the content of the memory pointed to by pa.

var
  a,b: Integer;
  pa, pb: ^Integer; //Pinteger / pointer to integer

a:= b;
pa := @a;
pb := @b;

if a=b then foo();
if pa=pb then bar();

foo will be executed, because a = b.

but bar will not be executed, because the addresses in the pointers are different (address of a of equal to address of b)
Title: Re: Can someone please explain pointers..
Post by: mas steindorff on May 03, 2010, 09:38:47 pm
A pointer is just points to the data.  A pointer to a byte and a pointer to complex data record are the same size. there are some (OS and platform) rules as to what you can point to kinda like what phone number you can have.

Just like phone numbers, the end result is not the number but who is on the other end.

The size of a pointer depends on the OS.
When I was young, all I needed to call my friend was the last 4 digit in my small town (in USA). I had to use 7 to call another town in the same state and 10 numbers (+1) to call out of state.  Today, the population is so large and my calling location (area code) can change that I always use the the 10 digit even if the 7 digit option is possible.  The same thing has happened to pointers so they can reach the any location without special handling.
some times it is the special handing that confuses people, kinda like when you call out of country but that sort handling is another topic  >:D

for more see wikipe..

http://en.wikipedia.org/wiki/Pointers
Title: Re: Can someone please explain pointers..
Post by: anna on May 04, 2010, 12:13:36 pm
......
var
  a: Integer;
  pa: ^Integer; //Pinteger / pointer to integer

pa := @a;

pa contains the address of "a" in memory.

....


Wait for minute. pa variable contains pointer, not address. Address is got by calling Ofs(a);

I agree that Pointers are very stupid device. For example I take 64 bytes of memory by
Code: [Select]
GetMem( pData , 64 );Now pData is a pointer on first byte of 64 . How to write some data in e.g. 32nd byte? Mystery, huh?
Title: Re: Can someone please explain pointers..
Post by: User137 on May 04, 2010, 01:09:02 pm
This is how i do it:
Code: [Select]
var
  data: PByte; // Pointer to dynamic byte-array
  i: integer;
begin
  data:=AllocMem(64); // reserve 64 bytes
  for i:=0 to 63 do
    data[i] := i; // Set data in dynamic array
  writeln(inttostr(data[32])); // prints out "32"
  FreeMem(data); // Free all (64) bytes
end;
Title: Re: Can someone please explain pointers..
Post by: Martin_fr on May 04, 2010, 01:16:02 pm
pa := @a;

pa contains the address of "a" in memory.
Wait for minute. pa variable contains pointer, not address. Address is got by calling Ofs(a);
"@" returns the address of a variable.

so pa contains the address. all pointers contain an address (or nil)


I agree that Pointers are very stupid device. For example I take 64 bytes of memory by
Code: [Select]
GetMem( pData , 64 );Now pData is a pointer on first byte of 64 . How to write some data in e.g. 32nd byte? Mystery, huh?


Ok I don't have a full tutorial for pointers at hand, I am sure somewhere there will be one.

the answer is
- for untyped pointer
(PByte(pdata) + 32)^

- for typed pointer (pointer to byte)
(pdata + 32)^

Which makes sense, if you accept that pdata contains the address of the first byte in the memory block.

as for pointer arithmetic, it depends on the type of pointer:
 (somepointer + 32)
does not mean 32 BYTES after somepointer. But it does mean 32 times the size of the element identified by the type of the pointer.

  
Title: Re: Can someone please explain pointers..
Post by: Troodon on May 04, 2010, 01:40:55 pm
Pointers and recursion are the greatest features in Pascal. Without pointers there would be no graphs, the most complex data structures. Without recursion some algorithms would be impossible to code. I could manage without OOP but not without those two features... Just kidding, OOP is awesome.

A pointer is a memory address. A pointer variable of type ^MyType is the beginning address of the memory segment where a value of type MyType is stored.

Using pointer variables ("pointers", for short) is simple:

- declare a pointer variable IntPtr that stores an Integer value:

Code: [Select]
type
  PInteger = ^Integer;

var
  IntPtr: PInteger;  // at this stage it is only an address


- create it:

Code: [Select]
IntPtr := New(PInteger);  // allocate memory for it
- assign a value to it:

Code: [Select]
IntPtr^ := 100;
- retrieve its value:

Code: [Select]
N := IntPtr^;
- destroy it:

Code: [Select]
Dispose(IntPtr);  // release memory allocated to it
Extras (you will seldom need these):

Code: [Select]
addr := @(IntPtr);  // memory address where it begins
size := SizeOf(Integer);  // size of allocated memory segment
N := Integer(IntPtr);  // value retrieved by type casting

To make things more interesting you could choose a pointer to a record type, ^MyRecord, instead of ^Integer. And obviously, MyRecord can include additional pointer variable fields along with static variable fields. That is how linked lists (stacks, queues), trees, and graphs are generated.

In particular, an object is an instance of a pointer variable. IMO, one of the confusing changes in Delphi (as compared to TP) was not making the pointer nature of the stock objects more explicit.
Title: Re: Can someone please explain pointers..
Post by: anna on May 04, 2010, 03:14:39 pm

the answer is
- for untyped pointer
(PByte(pdata) + 32)^

- for typed pointer (pointer to byte)
(pdata + 32)^

Which makes sense, if you accept that pdata contains the address of the first byte in the memory block.

as for pointer arithmetic, it depends on the type of pointer:
 (somepointer + 32)
does not mean 32 BYTES after somepointer. But it does mean 32 times the size of the element identified by the type of the pointer.

 


Over the pointers are not defined any operations other than testing equality and inequality.
Adding the integer will cause error of incompatibility types.

Pointers are not addresses because RAM address is dword value from $00000000 to $FFFFFFFF.

Pointers are pointers. It's individual type. Pascal doesn't have any other mechanism to write data to memory except through using pointers. I think would be better if pointer was integer value.
Title: Re: Can someone please explain pointers..
Post by: captian jaster on May 04, 2010, 03:40:11 pm
OH.....OK thats cool. ima try to find some examples...
This is how i do it:
Code: [Select]
var
  data: PByte; // Pointer to dynamic byte-array
  i: integer;
begin
  data:=AllocMem(64); // reserve 64 bytes
  for i:=0 to 63 do
    data[i] := i; // Set data in dynamic array
  writeln(inttostr(data[32])); // prints out "32"
  FreeMem(data); // Free all (64) bytes
end;
Thats cool. i didnt know i could reserve memory.. were did you learn that?

Thanks guys!
Title: Re: Can someone please explain pointers..
Post by: Martin_fr on May 04, 2010, 03:41:23 pm
- for untyped pointer
(PByte(pdata) + 32)^

- for typed pointer (pointer to byte)
(pdata + 32)^

Which makes sense, if you accept that pdata contains the address of the first byte in the memory block.

Over the pointers are not defined any operations other than testing equality and inequality.
Adding the integer will cause error of incompatibility types.

Pointers are not addresses because RAM address is dword value from $00000000 to $FFFFFFFF.

Pointer arithmetics are definitely defined and allowed.
You can add to a *typed* pointer (or an untyped pointer after casting it to a typed pointer)

The fact that memory on a modern PC is mapped, and each program is made to see it's own address-space does not oppose the fact that the data of the program is located at addresses (in this address space). So I stand by it: A pointer contains an address.
Title: Re: Can someone please explain pointers..
Post by: Troodon on May 04, 2010, 05:56:28 pm
Pointers are not addresses

You are technically right, anna. And it's like Martin said. Therefore, I reword:

"A pointer is a memory address." -> "A pointer holds the address at which data of the type type_identifier is situated." (cf. GNU Pascal docs (http://www.gnu-pascal.de/gpc/Pointer-Types.html))

Is there a difference?
Title: Re: Can someone please explain pointers..
Post by: JuhaManninen on May 04, 2010, 10:05:25 pm
Pointers are not addresses because RAM address is dword value from $00000000 to $FFFFFFFF.

What does that mean? Pointers are very much addresses! Yes.
I think every programmer should learn some assembly, or at least C, to understand what is actually going on.
This is a big problem with modern languages which have more and more abstraction from the actual processor level. If a programmer doesn't know how the code translates into low-level binary then he/she can make inefficient programs.

Juha
Title: Re: Can someone please explain pointers..
Post by: Troodon on May 04, 2010, 10:24:02 pm
This is a big problem with modern languages which have more and more abstraction from the actual processor level.

IMO that is actually a good thing ;) Another problem is, sometimes beginners try to edit memory directly instead of assigning values to variables. It's a bit like a child tinkering with the motherboard jumpers to learn computer programming.
Title: Re: Can someone please explain pointers..
Post by: Troodon on June 11, 2010, 09:54:40 pm
I have decided to learn C# just for fun and to see what all the fuss is about. Jeez, can they beat around the bush when trying to explain the difference between value and reference, or between class and struct! And to make things more complicated explanations also include the vague concepts of instance and object, while desperately trying to avoid any... reference to pointers. It's actually quite simple:

ObjectPascal    C#    comment
------------    ---    ---------
class    class*    object type    
object/instance    object/instance    instance of class =  the actual dynamic variable
value    value    content of a variable
pointer   reference    (variable containing) the address of a value

*To maintain an even stress on the developer, the C# type struct is similar but not identical to type class, it has methods but the constructor cannot be inherited, and it's a type for static not dynamic variables.

In C# the following types are reference types:

    - arrays
    - class
    - delegates
    - interfaces

And the following types are value types:

    - enum
    - struct

Obviously, "reference type" means dynamic variable and "value type" means static variable, in ObjectPascal. But adding the word "type" after "value" only creates confusion as "type" is an abstract concept while "value" involves an instance.

A few more reasons to like ObjectPascal ;)
Title: Re: Can someone please explain pointers..
Post by: anna on November 09, 2011, 04:08:42 am
Hello again.
I have some errors with SHFileOperation windows function.
Code: [Select]
uses windows;
var
    SH: TSHFileOpStruct;
    shpFrom_C67,shpTo_C67:pointer;
    path0,path1:string;

begin
      sh.hwnd:=0;
      sh.wFunc:=2;
      GetMem( sh.pFrom, $200  );FillChar(sh.pFrom^, $200, 0);
      GetMem( sh.pTo  , $200  );FillChar(sh.pTo^  , $200, 0);
      sh.pFrom:=pchar(Utf8ToAnsi(path0));
      sh.pTo:=pchar(Utf8ToAnsi(path1));
      sh.fFlags:=$251;
      sh.fAnyOperationsAborted:=longbool(0);
      sh.hNameMappings:=nil;
      sh.lpszProgressTitle:=nil;
      SHFileOperation(sh);
      system.assign(f2,Utf8ToAnsi(path0));
    end;           
Problem is that I must make pFrom & pToare  double-null terminated. How to do that? When I debugging I see that
before line      sh.pFrom:=pchar(Utf8ToAnsi(path0));
pFrom has an one address, and afrer line      sh.pFrom:=pchar(Utf8ToAnsi(path0));
pFrom has another memory address (and of course new-address^-data is NOT double-null terminated). Why? Is there a way to write some data into sh.pFrom^ whithout for-loop and whithout address changing.

I need that pFrom's GetMem address will be kept because I have $200 null-characters on that address. So even if first bytes will be some path, path automatically will be double(actually more then double, but [$200-length(path)>=$100]) null-terminated. Such solution as
Code: [Select]
for i:=1 to length(Utf8ToAnsi(path0)) do
 sh.pFrom^[i-1]:=Utf8ToAnsi(path0)[i];
Such solution as above is stupid!!!


I got added evidence that I was right, it's much better  if there would be some easy mechanism convert ''pointer-->address'' and ''pointer<--address''.
Title: Re: Can someone please explain pointers..
Post by: anna on November 09, 2011, 05:38:07 am
Ha-ha-ha! Next code even doesn't work
Code: [Select]
for i:=1 to length(Utf8ToAnsi(path0)) do
 sh.pFrom^[i-1]:=Utf8ToAnsi(path0)[i];

Error:
unit1.pas(498,19) Error: Illegal qualifier
And cursor shows 'i' (for-loop counter ):
sh.pFrom^[ i -1  ]:=Utf8ToAnsi(path0)[ i ];


  Why is qualifier  illegal?

Title: Re: Can someone please explain pointers..
Post by: anna on November 09, 2011, 05:54:31 am
I've found error. That should be:
Code: [Select]
for i:=1 to length(Utf8ToAnsi(path0)) do
 sh.pFrom{^}[i-1]:=Utf8ToAnsi(path0)[i];


Temporary i will use slowly for-loop, until invent better solution ...


Stupid pointers!
Title: Re: Can someone please explain pointers..
Post by: User137 on November 09, 2011, 06:56:02 am
Isn't UTF8 string sometimes longer than ANSI string? Ain't the whole point that it sometimes makes 1 character out of 2 bytes, so that it can support wider range of characters.

I don't know if this works.. but instead of for-loop, something like:
Code: [Select]
PChar( [code]sh.pFrom[0] ):=PChar(Utf8ToAnsi(path0));
Or first convert it into temporary string so you also know the real length it's reduced to.
Title: Re: Can someone please explain pointers..
Post by: avra on November 09, 2011, 10:21:40 am
http://www.google.com/search?q=pointers+pascal&ie=utf-8&oe=utf-8&aq=t
Title: Re: Can someone please explain pointers..
Post by: felipemdc on November 09, 2011, 10:29:11 am
Isn't UTF8 string sometimes longer than ANSI string? Ain't the whole point that it sometimes makes 1 character out of 2 bytes, so that it can support wider range of characters.

Yes, Anna should probably be using a W version of this Windows API, supposing it exists. Then she would need to convert the utf8 string to utf-16 using UTF8ToUTF16 and then copy the resulting string to the Windows record string array. I think that := will be able to copy a UnicodeString to a array of WideChar.

Quote
I don't know if this works.. but instead of for-loop, something like:
Code: [Select]
PChar( [code]sh.pFrom[0] ):=PChar(Utf8ToAnsi(path0));

No, I think that will fail. Windows API structures usually have real storage, not pointers to data.
Title: Re: Can someone please explain pointers..
Post by: anna on November 09, 2011, 01:23:30 pm
Isn't UTF8 string sometimes longer than ANSI string? Ain't the whole point that it sometimes makes 1 character out of 2 bytes, so that it can support wider range of characters.

Yes, Anna should probably be using a W version of this Windows API, supposing it exists. Then she would need to convert the utf8 string to utf-16 using UTF8ToUTF16 and then copy the resulting string to the Windows record string array. I think that := will be able to copy a UnicodeString to a array of WideChar.

I need not utf8 or unicode. I need ANSI and there is no problems with conversion. ANSI-string has 1-byted characters. For me conversion is clear. Thank you but I need not help with conversion.

***********************

There is only one func in Windows unit - SHFileOperation. But in OllyDBG I see SHFileOperationA, so compiler convert func to ansi version.
Title: Re: Can someone please explain pointers..
Post by: anna on November 09, 2011, 01:31:29 pm
Isn't UTF8 string sometimes longer than ANSI string? Ain't the whole point that it sometimes makes 1 character out of 2 bytes, so that it can support wider range of characters.

I don't know if this works.. but instead of for-loop, something like:
Code: [Select]
PChar( [code]sh.pFrom[0] ):=PChar(Utf8ToAnsi(path0));
Or first convert it into temporary string so you also know the real length it's reduced to.

unit1.pas(36,1) Error: Illegal type conversion: "Char" to "PChar"

So you are not allowed to make type conversion in left part of operator. It's similar as you would code : S1+S2:=S3;// compiler doesn't  understand such lines


Afrer that even if you code would be compiled , Pchar() is absolutely new variable (but just not declared and initializated). So it similar to
 NEW_VARIABLE:=PChar(Utf8ToAnsi(path0));
PChar( sh.pFrom[0] ):=NEW_VARIABLE;
Title: Re: Can someone please explain pointers..
Post by: zzamyy on April 03, 2020, 07:45:13 pm
cruz, on the Self pointer of class type is a signal that also is not in permission to read memory: pushing a SIVSEG error. is pushed by... well cannot access memory at address
Title: Re: Can someone please explain pointers..
Post by: zzamyy on April 03, 2020, 08:22:44 pm
Code: Pascal  [Select][+][-]
  1. program exPointers;
  2. var
  3.    number: integer;
  4.    iptr: ^integer;
  5.    y: ^word;
  6.  
  7. begin
  8.    number := 100;
  9.    writeln('Number is: ', number);
  10.    iptr := @number;
  11.    writeln('iptr points to a value: ', iptr^);
  12.    
  13.    iptr^ := 200;
  14.    writeln('Number is: ', number);
  15.    writeln('iptr points to a value: ', iptr^);
  16.    y := addr(iptr);
  17.    writeln(y^);
  18. end.
  19.  
  20.  

this is the most relevand info but still a permission is lost
Title: Re: Can someone please explain pointers..
Post by: 440bx on April 03, 2020, 08:44:22 pm
I think every programmer should learn some assembly, or at least C, to understand what is actually going on.
This is a big problem with modern languages which have more and more abstraction from the actual processor level. If a programmer doesn't know how the code translates into low-level binary then he/she can make inefficient programs.

Juha
If anything, this thread proves those words to be absolutely true. 

A lack or, poor understanding of pointers, severely limits a programmer's abilities to produce clean and efficient algorithms and, the set of methods that can be used to solve a problem.
Title: Re: Can someone please explain pointers..
Post by: noszone on June 23, 2021, 10:18:30 am
Beside of an explanation of pointers, there is one good question I guess. What is the real use case of pointers in standard business app dev? Or for example in which operations pointers are must have to use. I am quite new to pointers, realy interesting.
Title: Re: Can someone please explain pointers..
Post by: Zvoni on June 23, 2021, 10:29:24 am
Heap vs. stack when calling functions/passing params to functions?
Speed in general?
since basically any code you write gets "boiled" down to assembler-code, which is in its guts manipulation of memory-addresses resp. registers?
Using external API's (e.g. Winbloze-API)?
Title: Re: Can someone please explain pointers..
Post by: 440bx on June 23, 2021, 05:00:00 pm
Beside of an explanation of pointers, there is one good question I guess. What is the real use case of pointers in standard business app dev? Or for example in which operations pointers are must have to use. I am quite new to pointers, realy interesting.
In any kind of application, business or otherwise, the ability to use pointers adeptly gives the programmer a lot of flexibility in how to manage memory.  This in turn can greatly simplify code as well as having a noticeable impact on the program's performance.
Title: Re: Can someone please explain pointers..
Post by: alpine on June 23, 2021, 07:35:51 pm
In any kind of application, business or otherwise, the ability to use pointers adeptly gives the programmer a lot of flexibility in how to manage memory.  This in turn can greatly simplify code as well as having a noticeable impact on the program's performance.

On the other hand, there is a group of programming languages that explicitly prohibits memory management, i.e. they have no pointer concept. For example, the Java and .NET family. Don't even count the script languages.
Title: Re: Can someone please explain pointers..
Post by: 440bx on June 23, 2021, 08:45:26 pm
On the other hand, there is a group of programming languages that explicitly prohibits memory management, i.e. they have no pointer concept. For example, the Java and .NET family. Don't even count the script languages.
That's true but, for instance .net applications often feel clumsy and slow (unless on a very, very fast machine) the same is often true of Java programs.  Of course, for simple things they do ok but, when it comes to real programs they inevitably fall short of the mark.

I like and use AWK relatively often and, for some things it is wonderful but, I don't see something like Oracle or Photohop written in AWK given its totally absent facilities to manage memory.

Some programmers should work on their aversion towards pointers.  It's like an airline pilot being afraid of flying. 
Title: Re: Can someone please explain pointers..
Post by: alpine on June 24, 2021, 02:20:46 am
That's true but, for instance .net applications often feel clumsy and slow (unless on a very, very fast machine) the same is often true of Java programs.
Indeed they are.

  Of course, for simple things they do ok but, when it comes to real programs they inevitably fall short of the mark.
Putting aside most of the Android apps, some of them quite sophisticated, there are for example: Apache Hadoop and ASP.NET - frameworks for a large scale Web applications, Eclipse and NetBeans, M$ Visual Studio, M$ SQL Management Studio, etc. Very real (some of them - to my regret).

I like and use AWK relatively often and, for some things it is wonderful but, I don't see something like Oracle or Photohop written in AWK given its totally absent facilities to manage memory.
I don't know for AWK, but PHP have a lion share in the server side languages (>75%).

And all that without the pointer concept.
Title: Re: Can someone please explain pointers..
Post by: 440bx on June 24, 2021, 03:59:59 am
And all that without the pointer concept.
I'm not saying that many programs can't be written without using pointers but, a program that takes good advantage of the flexibility pointers provide will always have some advantages over one that doesn't. 

I don't know for AWK, but PHP have a lion share in the server side languages (>75%).
AWK is a text manipulation language.  Very simple, easy to learn and really useful to manipulate text.  I recommend it.  Good tool to have in one's toolbox.

Putting aside most of the Android apps, some of them quite sophisticated, there are for example: Apache Hadoop and ASP.NET - frameworks for a large scale Web applications, Eclipse and NetBeans, M$ Visual Studio, M$ SQL Management Studio, etc.
I cannot comment on some of the programs you mentioned but, I use Visual Studio regularly and it's rather far from being a speed demon (no surprise since it is a .net front end.)  It's got a lot of nice features but, it's a rather clumsy program.  I'd rather not use it but sometimes it is helpful.
Title: Re: Can someone please explain pointers..
Post by: noszone on June 24, 2021, 06:24:05 am
Probably most real use cases are image manipulations/comparisons? Video coding/decoding? As mentioned Windows API, other works with *dll 3rd party. I think the most hardware drivers are using pointers.
Title: Re: Can someone please explain pointers..
Post by: MarkMLl on June 24, 2021, 08:12:17 am
Probably most real use cases are image manipulations/comparisons? Video coding/decoding? As mentioned Windows API, other works with *dll 3rd party. I think the most hardware drivers are using pointers.

Pointers are pervasive: everything uses them.

However, everything is not the same as everybody. These days it is comparatively rare for an application programmer to have to use them, since by and large he will be more concerned with components and libraries written by system programmers which hide the details.

And that is entirely as it should be, since there are things that can be done with and to pointers which makes them dangerous in the hands of the inexperienced.

Some languages support references, which are very similar to pointers but somewhat safer since they are usually defined as not being amenable to arithmetic operations. So while you can increment a pointer to move through memory and potentially mess something up, generally speaking you can't do that with a reference.

As to the ten-year-old "what are they?" question, I've always found it useful to decouple pointers and the trees/lists with which they're usually lumped and then give a useful example.

Consider an operating system or library with an entry point that returns data on (say) its current version. There are two ways of handling that: either the API can define that the caller passes it a pointer to some memory into which it can copy the data, or the API defines that it will return a pointer to data that the program can then read. That's basically all there is to them.

MarkMLl
Title: Re: Can someone please explain pointers..
Post by: Zvoni on June 24, 2021, 08:29:57 am
Mark,
or refer to our example of a Pointer being like your credit-card of your bank-account from some weeks ago
Title: Re: Can someone please explain pointers..
Post by: MarkMLl on June 24, 2021, 09:26:39 am
Mark,
or refer to our example of a Pointer being like your credit-card of your bank-account from some weeks ago

When I started explaining this stuff to perplexed students people didn't have credit cards.

MarkMLl
Title: Re: Can someone please explain pointers..
Post by: alpine on June 24, 2021, 10:52:41 am
When I started explaining this stuff to perplexed students people didn't have credit cards.
I'm still remembering the time when the Pascal pointers were strongly typed and the things you can only do with them were new(), dispose() and =.
Now, the classes are the better substitute, you can create/free them, can't do arithmetic, etc. This topic makes me wonder about how long I haven't used the ^ symbol. It seems to have been a long time ago, because I don't remember well.
Title: Re: Can someone please explain pointers..
Post by: MarkMLl on June 24, 2021, 01:29:50 pm
I'm still remembering the time when the Pascal pointers were strongly typed and the things you can only do with them were new(), dispose() and =.
Now, the classes are the better substitute, you can create/free them, can't do arithmetic, etc. This topic makes me wonder about how long I haven't used the ^ symbol. It seems to have been a long time ago, because I don't remember well.

I wrote something using pointers a couple of days ago... and then redid it to use variant records. The final code is more verbose and I don't know how well the compiler is compacting it, but the result is something that the compiler can at least check fairly thoroughly.

Years ago, a major selling point of Delphi when compared with MS Visual BASIC was that a single language and toolset could be used to write both applications and lower-level extension components (MS required C++ for that). I think it could be argued that lower-level stuff requires pointers (and that less-capable references aren't flexible enough), but by now I am of the opinion that they should be forbidden to ordinary users.

MarkMLl
Title: Re: Can someone please explain pointers..
Post by: Zvoni on June 24, 2021, 01:57:10 pm
Some weeks ago i was doing some stuff in Excel VBA, extensively using pointers despite Visual Basic/VBA "officially" not supporting pointers (There are "undocumented" functions you can use to get some rudimentary pointer-functionality).
The stuff i was doing was, in a nutshell, removing an element from an array, and shifting the rest of the array "one down", which in Visual Basic/VBA is a nightmare to achieve with just the tools VBA officially offers.
Bottom Line: I agree with Mark, that pointers should be "hidden" from the ordinary user.
'Cause if you don't know what you're doing, you're going to create spectacular crashes, probably at the most unconvinient time.
Title: Re: Can someone please explain pointers..
Post by: Mr.Madguy on June 24, 2021, 03:26:06 pm
Address of variable in memory can both be constant and variable. [$40000000] = 3 is example of variable with constant address. But address can also be variable. For example when you access array element it's address is calculated like <Address of array> + <Size of element> * <Index>. Another opportunity - to store address of one variable in another variable. That's, what pointer actually is.
Title: Re: Can someone please explain pointers..
Post by: 440bx on June 24, 2021, 05:24:47 pm
I think hiding pointers from ordinary "users"/programmers encourages "clueless programming" resulting in programs that leave something to be desired.

Take a very simple program as an example, a checkbook program (not much to such a program.)  It would be expected that the program can present the information sorted by payee, date, check number, amount and possibly other criteria. 

Without using pointers sorting the checks is a real pain (not to mention slow if there are a lot of checks, e.g, a year's worth.)  The payee's name is a variably sized field, as will be the check's memo.  With pointers creating a list of checks sorted by a field is a piece of cake that takes very little code.  Without pointers, the programmer has to move variably sized fields around, that takes more code, it's more error prone and definitely slower due to all the necessary movement in memory.

Bottom line is, even something as simple as a checkbook program greatly benefits from using pointers.

Hiding pointers from a programmer is like hiding salt from a Chef.  Too much sodium is not good but so is not enough.
Title: Re: Can someone please explain pointers..
Post by: alpine on June 24, 2021, 05:39:00 pm
Address of variable in memory can both be constant and variable. [$40000000] = 3 is example of variable with constant address. But address can also be variable. For example when you access array element it's address is calculated like <Address of array> + <Size of element> * <Index>. Another opportunity - to store address of one variable in another variable. That's, what pointer actually is.
Speaking of pointers and arrays, the C language once startled me with the commutativity of it's subscript operator [].
Look at the 5-th line for example:
Code: C  [Select][+][-]
  1. int main()
  2. {
  3.     int a[10];
  4.     a[5] = 1;
  5.     5[a] = 1;
  6.     *(a + 5) = 1;
  7. }
All statements are equivalent:
Code: [Select]
Dump of assembler code for function main:
   0x00000000004004f6 <+0>:     push   %rbp
   0x00000000004004f7 <+1>:     mov    %rsp,%rbp
=> 0x00000000004004fa <+4>:     movl   $0x1,-0x1c(%rbp)
   0x0000000000400501 <+11>:    movl   $0x1,-0x1c(%rbp)
   0x0000000000400508 <+18>:    movl   $0x1,-0x1c(%rbp)
   0x000000000040050f <+25>:    mov    $0x0,%eax
   0x0000000000400514 <+30>:    pop    %rbp
   0x0000000000400515 <+31>:    retq   

So what is a pointer and what is an index? The answer is obvious for experienced, but maybe not so obvious for for a novice.

@440bx
Do you consider
Code: [Select]
var obj: TObject; as a pointer?

Because, AFAIK it is a reference. And you can use TObjectList or some other container from the template library to do that job. Without using the ^.
Title: Re: Can someone please explain pointers..
Post by: MarkMLl on June 24, 2021, 05:45:53 pm
Code: C  [Select][+][-]
  1.     a[5] = 1;
  2.     5[a] = 1;
  3.  
...
So what is a pointer and what is an index? The answer is obvious for experienced, but maybe not so obvious for for a novice.

It's not so much that it's obvious for the experienced, since those experienced only in Pascal would expect a syntax error.

It's obvious for those who have read the specification in detail, since the equivalence of pointers and arrays is defined (not IIRC in K&R, but in ANSI).

MarkMLl
Title: Re: Can someone please explain pointers..
Post by: MarkMLl on June 24, 2021, 06:02:25 pm
Take a very simple program as an example, a checkbook program (not much to such a program.)  It would be expected that the program can present the information sorted by payee, date, check number, amount and possibly other criteria. 

Without using pointers sorting the checks is a real pain...

Ah, the old "do not spindle" instruction :-)

There's various answers I might suggest, starting off with the null answer: "you don't need pointers, references are adequate". However...

If sorting is a job suitable for the inexperienced, how is it that it's taken 60 years for people to agree how to do it? You might notice that some of the sorting algorithms in Knuth assume that you have scratch tapes available...

And if sorting and searching are so trivial, how is it that virtually all textbooks had an error in their instructions as to how to do a simple binary chop until just a few years ago?

I agree that pointers are useful- not essential, but useful- for that sort of job. However I'd suggest that the fact that the operations benefit from pointers and that pointers are tricky beasts means that searching and sorting operations should always be encapsulated: as they are of course with FPC's TStringList.

I'd go further, and suggest that as a rule all pointers and many uses of references should be encapsulated, since that would allow issues like circular references to be removed from the application programming domain which would make reference counting memory managers more tractable.

MarkMLl
Title: Re: Can someone please explain pointers..
Post by: 440bx on June 24, 2021, 06:10:37 pm
@440bx
Do you consider
Code: [Select]
var obj: TObject; as a pointer?

Because, AFAIK it is a reference. And you can use TObjectList or some other container from the template library to do that job. Without using the ^.
I wouldn't consider that a pointer but, if instead of TObject, it had been "class of object" (I probably have the syntax wrong, I stay away from objects/classes like the plague)  then I would definitely consider that a pointer (a hidden one which makes it worse.)



ETA:

@MarkMLI, sorry somehow I missed your post.  Here are my comments on it.

If sorting is a job suitable for the inexperienced, how is it that it's taken 60 years for people to agree how to do it?
Designing sorting algorithms is definitely not for the inexperienced but, the inexperienced definitely want to use someone's sorting algorithm and, when they do, understanding pointers would quite likely serve them well.

And if sorting and searching are so trivial,
I didn't say that sorting and searching are trivial.  What I say is that even something as trivial as a checkbook program needs them.  Because of that, a programmer should, at least, be familiar with a number of algorithms for them which means they should have a reasonable understanding of pointers.

However I'd suggest that the fact that the operations benefit from pointers and that pointers are tricky beasts means that searching and sorting operations should always be encapsulated: as they are of course with FPC's TStringList.
The problem is that hiding pointers has consequences, many of them really bad.  Among those consequences is that there are too many programmers who don't really understand what is happening in their programs because they don't see the hidden pointers.  The result is, they are much more likely to make a mistake than someone who see what is happening behind the scenes.  Not too mention that the program's design will likely be "less than optimal".

<snip> which would make reference counting memory managers more tractable.
reference counting memory managers... just what a programmer needs, some "memory manager" to get in the way of the programmer's design. 

Compilers shouldn't try to program... that's what a programmer is for.  Compilers should generate object code that faithfully reflects what the programmer specified in the source.   The road to hell is paved with compiler's good intentions.
Title: Re: Can someone please explain pointers..
Post by: devEric69 on June 24, 2021, 08:59:07 pm
Basically, and to take an image, a pointer could be seen as one of the traffic panels on a crossroads, each pointing to its own distant city (i.e. each to its variable). The address of a pointer (for ex., @pTowardsBigCity) could be seen as the location of the city named "BigCity". Following a pointer, i.e. dereferencing it (pTowardsBigCity^), means to follow its direction, in order to reach the desired address, to arrive at the variable that we want to know, to see (i.e. to visit the desired city). There are many crossroads, each with its traffic panels. So, each crossroad, traffic panel, has its address too (for ex., unit1.@@pTowardsBigCity versus unit2.@@pTowardsBigCity), to possibly distinguish them from each other (practical, if they all point to the same city, in one region).
:)
Title: Re: Can someone please explain pointers..
Post by: MarkMLl on June 24, 2021, 09:02:55 pm
Basically, and to take an image, a pointer could be seen as one of the traffic panels on a crossroads, each pointing to its own distant city (i.e. each to its variable). The address of a pointer (for ex., @pTowardsBigCity) could be seen as the location of the city named "BigCity". Following a pointer, i.e. dereferencing it (pTowardsBigCity^), means to follow its direction, in order to reach the desired address, to arrive at the variable that we want to know, to see (i.e. to visit the desired city). There are many crossroads, each with its traffic panels. So, each crossroad, traffic panel, has its address too (for ex., @@pTowardsBigCityFromTrafficPanelNum1), to possibly distinguish them from each other (practical, if they all point to the same city, in one region).
:)

And to extend the metaphor, it's undesirable for anybody but the civic authority to start setting them up on their own account.

MarkMLl
Title: Re: Can someone please explain pointers..
Post by: alpine on June 24, 2021, 10:01:40 pm
I've just found what pointers and setters are.  8-)
Title: Re: Can someone please explain pointers..
Post by: devEric69 on June 24, 2021, 10:14:41 pm
I've just found what pointers and setters are.  8-)

Lol. Yes: more demonstrative than brilliant :D !
TinyPortal © 2005-2018