Page 1 of 1

negative indexes into arrays in C

Posted: Fri Aug 16, 2002 11:00 pm
by carbonBased
Perhaps an odd question:

How portable are negative indexes into an array in ANSI C?

In my memory management routines, I have two different kinds of stacks, one is expand up, and one expand down.  The expand up is obviously no problem... the stack pointer increases.  However, the expand down has the pointer starting at 0, and "increasing" into the negative side of zero.

In essence, stack[-1] is the second element in the stack.

This works in GCC perfectly fine... however, is this behaviour defined in ANSI C, or is GCC simply smart enough (or clueless enough...) to allow it to work?

I'm assuming that any/all C compilers will interpret array[index] into *(char *)(array + index), therefore, as long as index is signed, this should work.

Thanks,
Jeff

RE:negative indexes into arrays in C

Posted: Sun Aug 18, 2002 11:00 pm
by AnotherNewOS
Hi !

That sounds VERY SCARY to me.
I think you should better not use negative indexes on arrays.

IF the compiler makes that right, the danger of using
an unsigned if quite very high ...

Joerg