What is an Array in C Language
Categories: C language
An array is a type of data structure that stores a fixed-size of a homogeneous collection of data. In short, we can say that array is a collection of variables of the same type.
For example, if we want to declare 'n' number of variables, n1, n2...n., if we create all these variables individually, then it becomes a very tedious task. In such a case, we create an array of variables having the same type. Each element of an array can be accessed using an index of the element.
Let's first see how to pass a single-dimensional array to a function.
#include <stdio.h>
void getarray(int arr[])
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[5]={45,67,34,78,90};
getarray(arr);
return 0;
}
In the above program, we have first created the array arr[] and then we pass this array to the function getarray(). The getarray() function prints all the elements of the array arr[].
#include <stdio.h>
int *getarray()
{
int arr[5];
printf("Enter the elements in an array : ");
for(int i=0;i<5;i++)
{
scanf("%d", &arr[i]);
}
return arr;
}
int main()
{
int *n;
n=getarray();
printf("\nElements of array are :");
for(int i=0;i<5;i++)
{
printf("%d", n[i]);
}
return 0;
}
In the above program, getarray() function returns a variable 'arr'. It returns a local variable, but it is an illegal memory location to be returned, which is allocated within a function in the stack. Since the program control comes back to the main() function, and all the variables in a stack are freed. Therefore, we can say that this program is returning memory location, which is already de-allocated, so the output of the program is a segmentation fault.