473,397 Members | 2,099 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Array negative indexing

3
Expand|Select|Wrap|Line Numbers
  1. int a[3][3]={1,2,3,4,5,6,7,8,9};
  2. int j,i,s=10;
  3. for(i=0;i<3;i++) s=s-a[i][2-i]; printf("%d\n", s);
  4. for(j=0;j<3;j++) s=s-a[i][2-i]; printf("%d", s);

This is piece of C code, please some one can give the output

and pls EXPLAIN it ?

If possible, try to send a mail to <email_removed>

Thank you
Mar 21 '11 #1
8 2973
horace1
1,510 Expert 1GB
try printing the values of the array elemements indexed, e.g.
Expand|Select|Wrap|Line Numbers
  1. int a[3][3]={1,2,3,4,5,6,7,8,9};
  2. int j,i,s=10;
  3. for(i=0;i<3;i++) printf("%d ", a[i][2-i]);
  4. printf("\n");
  5. for(j=0;j<3;j++) printf("%d ", a[i][2-i]);
  6. printf("\n");
that should help you understand what is happening

in the following the for loop control variable is j but the array elements are indexed using i, should it be j ?
Expand|Select|Wrap|Line Numbers
  1. for(j=0;j<3;j++) s=s-a[i][2-i]; printf("%d", s);
also
Expand|Select|Wrap|Line Numbers
  1. int a[3][3]={1,2,3,4,5,6,7,8,9};
  2.  
a is a 2D so should be initialised as such. the gcc compiler gives the following warning
Expand|Select|Wrap|Line Numbers
  1. C:\temp\zz.c|3|warning: missing braces around initializer|
  2.  
Mar 21 '11 #2
donbock
2,426 Expert 2GB
Each loop executes only three times, so it is pretty easy to unroll them. Line 4 is certainly a typo, but I won't try to guess what it should be.
Expand|Select|Wrap|Line Numbers
  1. s = 10;    // line 2
  2. s -= a[0][2];   // line 3, i=0
  3. s -= a[1][1];   // line 3, i=1
  4. s -= a[2][0]    // line 3, i=2
  5. printf("%d\n", s);  // line 3
  6. s -= a[3][-1];  // line 4, j=0
  7. s -= a[3][-1];  // line 4, j=1
  8. s -= a[3][-1];  // line 4, j=2
  9. printf("%d\n", s);  // line 4
The behavior is undefined when you access past the bounds of an array; such as a[3][-1], where both indices are out-of-range. The compiler may give you a nice informative error message for undefined behavior, but the C Standard does not require that of it.

OK, I'll make a guess at what line 4 should have been. Line 3 traverses the right-to-left diagonal. Perhaps line 4 is meant to traverse the other diagonal.
Mar 21 '11 #3
kmon
3
Hi
when i tried this code (I used Dev C++) (outputs are given)
Expand|Select|Wrap|Line Numbers
  1. int a[3][3]={1,2,3,4,5,6,7,8,9};
  2.          int j,i,s=5;
  3.          for(i=0;i<3;i++) 
  4.                 s=s-a[i][2-i];
  5.          printf("%d\n",s); /* o/p is -10  */
  6.  
  7.          printf("a[%d][%d] is %d\n",2-i,i,a[2-i][i]);
  8.                            /* o/p is a[-1][3] is 1   */
  9.          printf("a[%d][%d] is %d\n",i,2-i,a[i][2-i]);
  10.                           /* o/p is a[3][-1] is 9  */
  11.          printf("a[%d][%d] is %d\n",2-i,i,a[2-i][i]);
  12.                           /* o/p is a[-1][3] is 1  */
  13.          printf("a[%d][%d] is %d\n",1-i,i,a[1-i][i]);
  14.                          /* o/p is a[-2][3] is 10  */
  15.          printf("a[-1][-1] is %d\n",a[-1][-1]);
  16.                 /* o/p is some RANDOM VALUE each time*/
  17.          printf("a[3][3] is %d\n",a[3][3]);
  18.                          /* o/p is 2686792 */
  19.  
I'm confused with this, since one cannot give array index out of the boundary....

Pls some one explain it...
thank u
Mar 24 '11 #4
Banfa
9,065 Expert Mod 8TB
No one has said that you can't give out-of-bounds array indexes, only that if you do you get undefined behaviour so it should be avoided. That is it is up to you as the programmer to make sure it doesn't happen, the compiler/computer does check for you.

Undefined behaviour is bad because the computer can literally do anything when this behaviour is invoked, including but not limited to
  • Work in what appears to be a sensible or correct fashion
  • Crash
  • Corrupt program data
  • Corrupt the hard disk
  • Make demons fly out of your nose

It is not constrained in anyway.

When you ran it you got the first item on that list but you have no guarantee that the same program run again will do the same thing.

Avoid undefined behaviour which means, among several other things, avoid access arrays outside their boundaries.
Mar 24 '11 #5
donbock
2,426 Expert 2GB
Did you write this code yourself or are you trying to understand code written by somebody else?
Do have any reason to believe the code is correct?
Mar 25 '11 #6
kmon
3
I got it from one of my friend, and myself checked it with Dev C++. (O/P is given in the code itself)
Mar 25 '11 #7
Banfa
9,065 Expert Mod 8TB
It doesn't matter what the output is, the behaviour is undefined, that means you can not rely on what is happening always happening.
Mar 25 '11 #8
donbock
2,426 Expert 2GB
The program is incorrect ... even if it happens to produce the desired output. The reason it is incorrect is that undefined behavior cannot be relied upon to be consistent. Perhaps you get the desired output today, but tomorrow you might get dramatically different output for the same inputs.
Mar 25 '11 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

47
by: VK | last post by:
Or why I just did myArray = "Computers" but myArray.length is showing 0. What a hey? There is a new trend to treat arrays and hashes as they were some variations of the same thing. But they...
22
by: VK | last post by:
A while ago I proposed to update info in the group FAQ section, but I dropped the discussion using the approach "No matter what color the cat is as long as it still hounts the mice". Over the last...
108
by: Bryan Olson | last post by:
The Python slice type has one method 'indices', and reportedly: This method takes a single integer argument /length/ and computes information about the extended slice that the slice object would...
3
by: K. Deepa | last post by:
Hi all, I am using postgresql7.4. How to handle arrays in plpgsql. How can I pass an array. Is it possible to retrieve values from an array by indexing it like argument : '{1,2,3}' Return...
19
by: buda | last post by:
Hello, Is the behaviour of indexing an array with a negative number (like a) defined by the standard?
29
by: shmartonak | last post by:
For maximum portability what should the type of an array index be? Can any integer type be used safely? Or should I only use an unsigned type? Or what? If I'm using pointers to access array...
32
by: Joe Rattz | last post by:
Hmmm, I wrote the following code. I want an array of bools and I want to intialize them to false. bool bits = new bool; foreach(bool bit in bits) { bit = false; } The compiler complains...
26
by: jacob navia | last post by:
Suppose an implementation where sizeof int == 4 sizeof void * == 8 sizeof long long == 8 When indexing an array array this would mean that arrays are limited to 2GB. To overcome this,
7
by: klays | last post by:
Hi all, I have created char array, when I use tab compiler shouts out: error: size of array 'tab' is negative I tried to cheat compiler and a little modify this code. Look at the code: ...
7
by: lovecreatesbea... | last post by:
Is it always legal to cast expressions of type of multi-dimension array to type of pointer? Including: T to T* , T to T* , T to T* , and so on... For example: int *mtxrot1d(int *p,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.