Complete.Org: Mailing Lists: Archives: freeciv-dev: January 2001:
[Freeciv-Dev] Re: (offtopic) C subscripts; was Re: Compiler-war
Home

[Freeciv-Dev] Re: (offtopic) C subscripts; was Re: Compiler-war

[Top] [All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index] [Thread Index]
To: freeciv development list <freeciv-dev@xxxxxxxxxxx>
Subject: [Freeciv-Dev] Re: (offtopic) C subscripts; was Re: Compiler-warnings
From: Dirk Stoecker <stoecker@xxxxxxxxxxxxxx>
Date: Thu, 25 Jan 2001 08:45:01 +0100 (MET)

On Wed, 24 Jan 2001, David Pfitzner wrote:

> Negative subscript values have just the same semantics as
> non-negative ones -- its just pointer arithmetic:
>    a[b]  =  *(a + b)
> Everything is fine as long as you don't point outside a 
> "valid region of memory" <insert technical definition here>.
> 
[...]
> 
> This has undefined behaviour because you are dereferencing
> outside the memory range allocated for 'a'; anything could
> happen.
> 
> Try:
>       int *b = a + 5;
>       ...
>       printf("b[-1]=%d\n", b[-1]);
> 

This is required often, when doing pointer arithmetics and accessing
fields, which have already been processd (e.g. when using *(p++)) and
for any reason needing it again.

But I prefer to use *(p-1) instead of p[-1], as this is much better style.

Ciao
 ____  _ _  ____  _ _    _ _  ____
|    |  |  |    |  | \  / |  |    | the cool Gremlin from Bischofswerda
|  __   |   ____|  |  \/  |  |    | WWW: http://home.pages.de/~stoecker/
|    |  |  |       |      |  |    | PGP key available on www page.
|____| _|_ |____| _|_    _|_ |____| I hope AMIGA never ends to make fun!




[Prev in Thread] Current Thread [Next in Thread]