1

I am just trying out arrays in c.In which i have following fundamental doubts?

#include <stdio.h>

int main()
{
    int a[5]={1,2,3,4,5};
    a[45]=28; // trying to access the random array element which is out of bound 
    printf("\n value at a[5] is %d",a[5]);
    printf("\nvalue at a[45] is %d",a[45]);
    printf("\nvalue at a[78] is %d",a[78];
    return 0;
}

The above program compiles successfully and produces following output.

value at a[5] is 1234355   // some ando address
value at a[45] is 28       // which i have assigned
value at a[78] is 0

my question are

i) when i am accessing array element out of bound .whys it is not generating any error?

ii) For char array eg : char[10]= {'1','2','3','4','5','6','7','8','9','0'};last element of the array will be '\0' added by compiler .is any like that for integer array?if not why?

iii) is it possible to redefine the array?

manish
  • 1,450
  • 8
  • 13
tamil_innov
  • 223
  • 1
  • 7
  • 16

1 Answers1

2

These are not "doubts", they are questions.

  1. Because C doesn't have bounds-checking. It will let you do what you want, pretty much. This code is undefined behavior, anything could happen. That it "works" is just luck.
  2. No, it's only for strings, and won't happen if the literal's length matches the arrays exactly like in your case. If you do char foo[] = "abc"; then foo[3] will be added as '\0', but if you do char foo[3] = "foo"; then foo[3] is an invalid access since the array only has three values. The last value is foo[2] which will be 'o', your initializer is not overwritten by the compiler, so in this case foo is not a valid string.
  3. Not sure what you mean by "redefine", but no you cannot re-define any variables in C, not in the same scope at least. You can "alias" them with a new scope, but that's pretty ugly and doesn't buy you much in practice.
unwind
  • 391,730
  • 64
  • 469
  • 606