简体   繁体   中英

Arrays in C program

Here is my C Program Code :

#include<stdio.h>

unsigned int count = 1; 

int main(void)
{
  int b = 10;
  int a[3];
  a[0] = 1;
  a[1] = 2;
  a[2] = 3; 

  printf("\n b = %d \n",b);
  a[3] = 12; 
  printf("\n b = %d \n",b); 

  return 0;
}

And the output as

b=10 
b=12

Can anyone explain why it is and the reason behind the error.

You are writing beyond the bounds of the array. This would invoke undefined behavior .

You are writing at a[3] = 12; to an out of bound index, which is UB and since its UB it means anything can happen so chances are you have just over-written the value at a[3] which is the location of b .

Your program has undefined behavior . Depending on your result, your memory looked like this:

  a[0]   a[1]   a[2]    b   
+------+------+------+----+
|  1   |  2   |  3   | 12 |
+------+------+------+----+

b is the same as a[3] since it "sits" next to it in the memory.

This is only one possible scenario, your program could has a "segmentation fault" or anything else as well.

It's because you're accessing a[3] , which is the 4th element, but you only defined an array of size 3. As a result, you're getting a pointer to garbage data, which happens to point to the memory location of b . So when you assign a[3] , you're assigning the memory location of b :

#include<stdio.h>

unsigned int count = 1; 

int main(void)
{
  int b = 10;
  int a[3];
  a[0] = 1;
  a[1] = 2;
  a[2] = 3; 

  printf("\n b = %d \n",b);
  a[3] = 12; 

  printf("\n b = %d \n",b); 

 return 0;
}

The pointer memory locations point to the same thing for a[3] and b :

b = 10 
a[3]:0xa
b:0xa

b = 12 

Now try actually creating an array with four elements. Change a[3] to a[4] , so that a[3] isn't a garbage location. You'll see it works.

The so-called "Undefined Behaviour" can include many kinds of behaviour. Amongst them can be:

  • nothing bad happens
  • you get a segmentation fault (or any other access violation)
  • you destroy/tamper other data structures.

You have the latter here: the variable b happens to be in memory directly after the array, so it is modified due to this wrong access.

Maybe you can define a pointer to the address of a[3], and output it. Then you will know the answer.

because if you prints address of both variable b and a[3] like,

printf("%u",&b);  
printf("\n %u",&a[3]); 

then it gives same output for both variable address

Your program results in undefined behavior, answers here explain this "undefined behavior" trying to give some meaning to your output,which is not always true. In-fact i try to run your program and I can see b is printed 10 in both printf and finally i get run time error (I used Visual Studio 2010)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM