noobUser
noobUser

Reputation: 43

Array values at negative one

Are there any repricussions having a value in an array stored at -1? could it affect the program or computer in a bad way? I am really curious, I'm new to programming and any clarification I can get really helps, thanks.

Upvotes: 0

Views: 125

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320401

There's no way to store anything in an array object at index -1. A mere attempt to obtain a pointer to that non-existing element results in undefined behavior.

Negative indices (like -1) may appear in array-like contexts in situations when base pointer is not the array object itself, but rather an independent pointer pointing into the middle of another array object, as in

int a[10];
int *p = &a[5];

p[-1] = 42; // OK, sets `a[4]`
p[-2] = 5; // OK, sets `a[3]`

But any attempts to access non-existent elements before the beginning of the actual array result in undefined behavior

a[-1]; // undefined behavior
p[-6]; // undefined behavior

Upvotes: 7

Predelnik
Predelnik

Reputation: 5246

You see if you are trying to take element of array by pointing some value in brackets, basically you're specifying offset (multiplied by size of allocated type) from memory address. If you've allocated array in a typical way like int *a = new int[N], memory you're allowed to use is limited from address a until a + <size of memory allocated> (which in this case sizeof (int) * N), so by trying to get value with index -1 you are getting out of bounds of your array and it certainly will lead you to error or possible program crash.

There's of course a chance that your memory pointer is not the one at the beginning of some allocated sequence, like (considering previous example) int *b = a + 1, in this case you may (at least compiler allows that) take value of a[-1] and it would be valid, but since it's pretty hard to manage correctness of code like this I would still recommend against it.

Upvotes: 0

Related Questions