[Tutor] pointer puzzlement

Alan Gauld alan.gauld at btinternet.com
Sat May 9 00:26:16 CEST 2015


On 08/05/15 19:10, Jim Mooney Py3.4.3winXP wrote:
> On 7 May 2015 at 18:42, Dave Angel <davea at davea.name> wrote:
>
>> Python doesn't have pointers
>
>
> So what is the difference between a python name and a pointer?

OK, This could get deepo.
Lets start with the supoerficial...

A pointer (in most languiages) is a named alias for a memory address.
That is a name that is a specidic memory location. At least in C and 
some other languages.

That means you can, in C , declare a variable (say p) to be a pointer
to some array of objects and it is simply the memory address of the 
first object in the array. The second objects address is therefore 
p+sizeof(o) where 'o' is the object type of the array.

You can in fact write code like this in C (and frequently do):

int p*;  // declare p to be a pointer to an integer
int ia[] = {1,2,3,4,5,6,7,8,9,0};  // an array of 10 integers
p = ia;   # p holds the address in ia, ie its first element

printf("%d\n", p);  // print the object, ie ia[0]
printf("%d",p+3);   // print the 4th object ie ia[3]

So p is a pointer to an integer. And an array is a sequence
of integers in memory so you can access subsequent memory
locations by adding numbers to p. (The compiler multiplies
the number by the size of the type of p to get the actual
memory address.)

In other languages (eg Pascal) pointers are slightly more
abstract but not much. They are more like C++ references
than memory addresses, but the end result is much the same:
they are very tightly  tied to the physical concepts of
memory versus variables.

Now in contrast...
In Python a name is a much more abstract concept and is
just a label that is attached to an object. How the label
gets attached is an entirely abstract and implementation
specific concept. In practice its usually via a dictionary
so that a variable is a name which is a key of a dictionary.
The corresponding value is an object or, (crucially) maybe
a pointer to an object. But the name is not the pointer
it's the corresponding value that (may be) a pointer.

So this Python code (compare to the C above) makes no sense:

aList = [1,2,3,4,5,6,7,8,9,0]
print aList_+ 3

aList is not a pointer to the start of a sequence of
objects in memory. aList is a key to a dictionary
that holds a reference to a list of objects. And adding
3 to a key in a dictionary is not a sensible operation.

PS.
I'm writing this at 11:30pm and I've just drunk a full
bottle of (very good!) red wine all by myself (how sad!).
If it makes no sense, my apologies, I'll review it in
the morning!!! :-(

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list