can we store array value like this

a[-50];
a[-49]=80;
a[-2]=90;

Recommended Answers

All 9 Replies

Not in C or C++. Index values must be positive.

EDIT: @AD: I seriously thought so too, but I googled it first.
SECOND EDIT: @rithish: DO NOT DO THIS UNLESS YOU KNOW WHAT YOU'RE DOING!
Apparently, you can. I'd try it first on your compiler just to be sure.
Make sure it's pointed at a valid memory location that has been allocated.
http://stackoverflow.com/questions/3473675/negative-array-indexes-in-c

#include <stdio.h>

int main(){
    int array[16];
    int *ptr=array+8;
    int i;
    for(i=0;i<16;i++)
        array[i]=i;
    for(i=-8;i<8;i++)
        printf("ptr[%d]:%d\t", i, ptr[i]);
    return 0;
}

(Tested in MinGW 4.7 on Windows XP x86, then GCC 4.6 in Ubuntu x64)

ooh superb DeanMSands3 thanks dude

Not in C or C++. Index values must be positive.

As long as the index refers to some location in the array's boundaries, indices may be positive or negative. For example:

int a[] = {1, 2, 3, 4, 5};
int *p = a + 2;

printf("%d\n", p[-1]); /* Perfectly legal and portable! */

Whether this is useful or not is up for debate. ;)

Yes, but that was not the question. there is no such index as a[-1]

Yes, but that was not the question.

I fail to see how the question couldn't be interpreted as such. In fact, I can think of several perfectly valid interpretations. Reread the OP, this time without making assumptions.

there is no such index as a[-1]

You don't know that; the definition of a was not provided. None of the OP's statements were invalid as written.

You don't know that;

I was referring to the code you posted

ooh stop ur fights this thread has been solved thanks to all of u.please solve my next thread

I was referring to the code you posted

I can rename the variables to be perfectly in line with the OP if it makes my point easier to digest. :rolleyes:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.