Design for slices

D-Man dsh8290 at rit.edu
Thu Feb 1 19:35:29 EST 2001


On Thu, Feb 01, 2001 at 09:54:55AM +1100, Ben Catanzariti wrote:
| I am fairly sure this came about due to the fact you are defining a position
| of a pointer, not an object ie. a letter in a string. So position x[0] means
| the pointer has not moved or has a null value and will occur directly before
| the first letter in a string....
| 
| Some one please correct me if i am wrong ... I am sure you will ;)

I think you are correct, for C.  In C a string can be declared as
either:

char[] /* array of characters */
char*  /* pointer to a character */

The char* can either be a pointer to a single character, or a pointer
to an array of characters.  Thus the following equivalences:

char[10] str1 ;
char*    str2 ;
/* string init not shown */

str1[0] == *str2
str[n] == *(str2 + n)

It also makes the following loop rather short and cute (with the NULL
terminator, of course) :

/* start off 1 element before the array */
char* ptr = str2-1 ; /* or str1 if you prefer */

/* advance the pointer to the end of the string */
while( *(++ptr) ) ;


Along the lines of Alex' example, during my beginning Comp. Sci.
courses I was given the exercise of implementing a 2d array (table).
This was done in Eiffel.  Following the Eiffel principles, the client
would provide both the lower and upper indices.  Not requiring the
client to use zero-based indexing created more work in my ARRAY2 class
because of the mathematical reasons already stated.

-D


| 
| "Gustaf Liljegren" <gustafl at algonet.se> wrote in message
| news:959uue$k02$1 at cubacola.tninet.se...
| > I'm learning Python and have a question about defining ranges/slices in
| > strings. I can't find any defence for what looks like a poor design, so I
| > have to ask. Why is the first character in the string x defined as x[0]
| and
| > not x[1]? This looks just like the typical geek thinking that I'm trying
| to
| > avoid with Python.
| >
| > Gustaf
| 




More information about the Python-list mailing list