I have observed that memory allocated for array seems to be dynamic.
Here is the sample code I found in this tutorial:
#include <stdio.h>
main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
n = n + 1;
while( j >= k){
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = item;
printf("The array elements after insertion :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
and sample output:
The original array elements are : LA[0]=1 LA[1]=3 LA[2]=5 LA[3]=7 LA[4]=8 The array elements after insertion : LA[0]=1 LA[1]=3 LA[2]=5 LA[3]=10 LA[4]=7 LA[5]=8
How its working I did not get.
To add on to the other answers, C/C++ do not do any bounds checking for arrays.
In this case you have a stack allocated array, so as long as your index does not leave stack space, there will be no "errors" during runtime. However, since you are leaving the bounds of your array, it is possible that you may end up changing the values of other variables that are also allocated in the stack if it's memory location happens to be immediately after the allocated array. This is one of the dangers of buffer overflows and can cause very bad things to happen in more complex programs.
The code has a buffer overflow bug! Arrays in C cannot be extended! You need to allocate enough space when you declare/define it.
You can declare additional space by supplying a size in the declaration:
LA
will now have room for 10 elements with index 0 through 9.If you want more flexibility you should use a pointer and
malloc
/calloc
/realloc
to allocate memory.Note:
There is a second bug in the copying. The loop starts one step too far out.
With
j
starting at 5 and assigning indexj+1
the code assignsLA[6]
, which is the 7th element. After the insertion there are only 6 elements.My conclusion from these 2 bugs is that the tutorial was neither written nor reviewed by an experienced C programmer.
First, a general statement, for an array defined without explicit size and initialized using brace-enclosed initializer, the size will depend o the elements in the initializer list. So, for your array
size will be
5
, as you have 5 elements.C uses 0-based array indexing, so the valid access will be 0 to 4.
In your code
trying to access index
6
, (5+1
) which is out of bound access. This invokes undefined behavior.Output of a code having UB cannot be justified in any way.
That said,
main()
is technically an invalid signature as per latest C standards. You need to use at leastint main(void)
to make the code conforming for a hosted environment.