Consider this code:
#include <stdio.h>
int main() {
static arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
for(int i = 2; i < 50; i++)
{
arr[arr[i]] = arr[i] + i;
}
for(int i = 0; i < 50; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
It gives successful output for 50 elements. But the array had 8 elements. WHY no segmentation fault??
and this code:
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
for(int i = 2; i < 50; i++)
{
arr[arr[i]] = arr[i] + i;
}
for(int i = 0; i < 50; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
It gives segmentation fault as expected.
Please explain to me what static arr[]
is doing. I'm a beginner and as far as I know, a data type is required. Here, instead static
is used.
In the first code, I don't really understand what is happening.