You are here:

C/C arrays

Advertisement


Question
Hello,

I have a problem and I don't know how to explain it. I have a projects and it uses a -1 index, like this:
c_cscanline[n_s][-1]=c_cscanline[n_s][0]=c_pscanline[n_s][1];

Do you happen to know how is this possible? the project is on JPEG-LS the code is open source.

Thank you very much


Kind Regards,
Criss

Answer
Hello Criss

It's possible to have a -1 index. The compiler will accept it but it is not a good idea. I would say it is a mistake in the code.

c_cscanline[n_s][-1] is simply the memory location before c_cscanline[n_s][0]. If n_s happens to be 0 also, then the statement will be writing outside of the array and corrupting memory.

If you want to know what is happening, the best way is to make a short test program, like this:

#include <stdio.h>
int main()
{
   char arr[5][5];
   char* p = &arr[4][0];
   printf("address at 4,0  %d\n", p);
   p = &arr[4][-1];
   printf("address at 4,-1 %d\n", p);
   p = &arr[3][4];
   printf("address at 3,4  %d\n", p);
}

On my machine, the printout is
address at 4,0  1245016
address at 4,-1 1245015
address at 3,4  1245015

So you can see that the address of array element 4,-1 is just before array element 4,0. It is the same address as element 3,4 which is the last element of the previous "row".

I hope that makes it clear.
Best regards
Zlatko  

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.