arrays: negative index values

M

Mantorok Redgormor

Are negative values used as an index for an array valid or is this
illegal and if it is illegal where does it state it in the standard?

The only way I can see where a negative value can be used is if you
assign an address to a pointer to the type of array where that address
is not the lowest address of the array(the address the array name
decays to)

Something like:

int *foo;
int bar[10] = {0};

foo = bar+1;

printf("%d\n", foo[-1]);

would be perfectly legal?

However, bar[-1] would not?
 
D

Derk Gwen

(e-mail address removed) (Mantorok Redgormor) wrote:
# Are negative values used as an index for an array valid or is this
# illegal and if it is illegal where does it state it in the standard?

It's okay as long the address is within one allocated array.

# int *foo;
# int bar[10] = {0};
#
# foo = bar+1;
#
# printf("%d\n", foo[-1]);
#
# would be perfectly legal?

Yes.

bar[-1] or foo[-2] is undefined, since that's outside the allocation of bar,
as would be foo[9] or bar[10].
 
R

Richard Bos

Something like:

int *foo;
int bar[10] = {0};

foo = bar+1;

printf("%d\n", foo[-1]);

would be perfectly legal?

Yes. tick[tock] is required to be the same thing as *(tick+tock),
provided one of those is an integer and the other a pointer - _any_
integer and _any_ pointer. The only restriction is that tick+tock must
point either at a valid object, or at the memory location just after a
valid object.
This means that your code is correct, because it is equivalent to
*(foo-1), which is currently equal to *bar.
However, bar[-1] would not?

Indeed it wouldn't, but only because bar-1 does not point at an object.
Syntactically it's quite correct, but it invokes undefined behaviour.

Richard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top