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

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

[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: David Pfitzner <dwpfitzner@xxxxxxxxx>
Date: Wed, 24 Jan 2001 19:37:03 -0800 (PST)

Raimar Falke <hawk@xxxxxxxxxxxxxxxxxxxxxxx> wrote: >

> [ Negative subscript values? Is this a gnu extension? What are the
> semantics? 

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>.

Eg, see also:

http://www.eskimo.com/~scs/C-faq/q6.17.html
http://www.eskimo.com/~scs/C-faq/q6.11.html

> What would you expect from:
> -------
> #include <stdio.h>
> 
> int main()
> {
>     int x,arr[10],y,i;
> 
>     for(i=0;i<10;i++)
>         arr[i]=i;
>     x=42;
>     y=43;
>     printf("[-1]=%d\n",arr[-1]);
>     printf("[10]=%d\n",arr[10]);
> 
>     return 0;
> }

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]);

[Incidently q6.17 referenced above has comments which are related 
(but maybe not directly relevant) to my concern about storing 
arbitrary ints in pointers.]

-- David

__________________________________________________
Do You Yahoo!?
Yahoo! Auctions - Buy the things you want at great prices. 
http://auctions.yahoo.com/



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