4th Unit
4th Unit
Array in C is one of the most used data structures in C programming. It is a simple and fast
way of storing multiple values under a single name. In this article, we will study the different
aspects of array in C language such as array declaration, definition, initialization, types of
arrays, array syntax, advantages and disadvantages, and many more.
What is Array in C?
C Array Declaration
In C, we have to declare the array like any other variable before using it. We can declare an
array by specifying its name, the type of its elements, and the size of its dimensions. When we
declare an array in C, the compiler allocates the memory block of the specified size to the array
name.
or
#include <stdio.h>
int main()
{
return 0;
}
C Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the array is
declared or allocated memory, the elements of the array contain some garbage value. So, we
need to initialize the array to some meaningful value. There are multiple ways in which we can
initialize an array in C.
array_name [index];
One thing to note is that the indexing in the array always starts with 0, i.e., the first element is
at index 0 and the last element is at N – 1 where N is the number of elements in the array.
Example of Accessing Array Elements using Array Subscript Operator
int main()
{
return 0;
}
Types of Array in C
There are two types of arrays based on the number of dimensions it has. They are as follows:
Syntax of 1D Array in C
array_name [size];
Example of 1D Array in C
int main()
{
// 1d array declaration
int arr[5];
2. Multidimensional Array in C
Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of
the popular multidimensional arrays are 2D arrays and 3D arrays. We can declare arrays with
more dimensions than 3d arrays but they are avoided as they get very complex and occupy a
large amount of space.
A. Two-Dimensional Array in C
A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions. They
can be visualized in the form of rows and columns organized in a two-dimensional plane.
Syntax of 2D Array in C
array_name[size1] [size2];
Here,
Example of 2D Array in C
int main()
{
// declaring and initializing 2d array
int arr[2][3] = { 10, 20, 30, 40, 50, 60 };
printf("2D Array:\n");
// printing 2d array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}
// driver code
int main()
{
int arr[5] = { 10, 20, 30, 40, 50 };
printf("Size of Array in main(): %d\n", sizeof(arr));
printArray(arr);
return 0;
Advantages of Array in C
C Structures:
The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the C
programming language. The items in the structure are called its member and they can be of any
valid data type.
C Structure Declaration
We have to declare structure in C before using it in our program. In structure declaration, we
specify its member variables along with their datatype. We can use the struct keyword to
declare the structure in C using the following syntax:
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
The above syntax is also called a structure template or structure prototype and no memory is
allocated to the structure in the declaration.
C Structure Definition
To use structure in our program, we have to define its instance. We can do that by creating
variables of the structure type. We can define structure variables using two methods:
1. Structure Variable Declaration with Structure Template
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;
C language allows us to insert one structure into another as a member. This process is called
nesting and such structures are called nested structures. There are two ways in which we can
nest one structure into another:
In this method, the structure being nested is also declared inside the parent structure.
Example
struct parent {
int member1;
int member_str1;
char member_str2;
...
...
In this method, two structures are declared separately and then the member structure is nested
inside the parent structure.
Example
struct member_str {
int member_str1;
char member_str2;
...
}
struct parent {
int member1;
...
One thing to note here is that the declaration of the structure should always be present before
its definition as a structure member. For example, the declaration below is invalid as the struct
mem is not defined when it is declared inside the parent structure.
struct parent {
struct mem a;
};
struct mem {
int var;
};
We can access nested Members by using the same ( . ) dot operator two times as shown:
str_parent.str_child.member;
// forward declaration
#include <stdio.h>
struct child {
int x;
char c;
};
struct parent {
int a;
struct child b;
};
// driver code
int main()
{
struct parent var1 = { 25, 195, 'A' };
// accessing and printing nested members
printf("var1.a = %d\n", var1.a);
printf("var1.b.x = %d\n", var1.b.x);
printf("var1.b.c = %c", var1.b.c);
return 0;
Uses of Structure in C
Limitations of C Structures
In C language, structures provide a method for packing together data of different types. A
Structure is a helpful tool to handle a group of logically related data items. However, C
structures also have some limitations.
File handing in C is the process in which we create, open, read, write, and close operations on a
file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(),
etc. to perform input, output, and many different C file operations in our program.
So far the operations using the C program are done on a prompt/terminal which is not stored
anywhere. The output is deleted when the program is closed. But in the software industry, most
programs are written to store the information fetched from the program. The use of file
handling is exactly what the situation calls for.
In order to understand why file handling is important, let us look at a few features of using
files:
Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and
anytime providing high reusability.
Portability: Without losing any data, files can be transferred to another in the computer system.
The risk of flawed coding is minimized with this feature.
Efficient: A large amount of input may be required for some programs. File handling allows
you to easily access a part of a file using few instructions which saves a lot of time and reduces
the chance of errors.
Storage Capacity: Files allow you to store a large amount of data without having to worry
about storing everything simultaneously in a program.
Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are as
follows:
Text Files
Binary Files
1. Text Files
A text file contains data in the form of ASCII characters and is generally used to store a stream
of characters.
Each line in a text file ends with a new line character (‘\n’).
It can be read or written by any text editor.
They are generally stored with .txt file extension.
Text files can also be used to store the source code.
2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They
contain data that is stored in a similar manner to how it is stored in the main memory.The
binary files can be created only from within a program and their contents can only be read by a
program.
C File Operations
C file operations refer to the different possible operations that we can perform on a file in C
such as:
Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
Opening an existing file – fopen()
Reading from file – fscanf() or fgets()
Writing to a file – fprintf() or fputs()
Moving to a specific location in a file – fseek(), rewind()
Closing a file – fclose()
Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path along with
the required access modes.
Syntax of fopen()
Parameters
file_name: name of the file when present in the same directory as the source file.
Otherwise, full path.
Return Value
If the file is opened successfully, returns a file pointer to it.
File opening modes or access modes specify the allowed operations on the file to be opened.
They are passed as an argument to the fopen() function. Some of the commonly used file
access modes are listed below:
Opening
Modes Description
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
r a pointer that points to the first character in it. If the file cannot be opened fopen( )
returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
Open for writing in text mode. If the file exists, its contents are overwritten. If the file
w
doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
Open for writing in binary mode. If the file exists, its contents are overwritten. If the file
wb
does not exist, it will be created.
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
a a pointer that points to the last character in it. It opens only in the append mode. If the
file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
Open for append in binary mode. Data is added to the end of the file. If the file does not
ab
exist, it will be created.
Searches file. It is opened successfully fopen( ) loads it into memory and sets up a
r+
pointer that points to the first character in it. Returns NULL, if unable to open the file.
Open for both reading and writing in binary mode. If the file does not exist, fopen( )
rb+
returns NULL.
Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new
w+
file is created. Returns NULL, if unable to open the file.
wb+ Open for both reading and writing in binary mode. If the file exists, its contents are
Opening
Modes Description
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
a pointer that points to the last character in it. It opens the file in both reading and append
a+
mode. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the
file.
Open for both reading and appending in binary mode. If the file does not exist, it will be
ab+
created.
As given above, if you want to perform operations on a binary file, then you have to append ‘b’
at the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have to use
“a+b”.
C
#include <stdio.h>
#include <stdlib.h>
int main()
// fopen
FILE* fptr;
if (fptr == NULL) {
exit(0);
return 0;
Output
The file is not opened because it does not exist in the source directory. But the fopen() function
is also capable of creating a file if it does not exist. It is shown below
Create a File in C
The fopen() function can not only open a file but also can create a file if it does not exist
already. For that, we have to use the modes that allow the creation of a file if not found such as
w, w+, wb, wb+, a, a+, ab, and ab+.
FILE *fptr;
fptr = fopen("filename.txt", "w");
C
#include <stdio.h>
#include <stdlib.h>
int main()
// file pointer
FILE* fptr;
"exit now");
exit(0);
else {
return 0;
Output
The file read operation in C can be performed using functions fscanf() or fgets(). Both the
functions performed the same operations as that of scanf and gets but with an additional
parameter, the file pointer. There are also other functions we can use to read from a file. Such
functions are listed below:
Function Description
fscanf() Use formatted string and variable arguments list to take input from a file.
So, it depends on you if you want to read the file line by line or character by character.
Example:
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
The getc() and some other file reading functions return EOF (End Of File) when they reach the
end of the file while reading. EOF indicates the end of the file and its value is implementation-
defined.
Note: One thing to note here is that after reading a particular part of the file, the file pointer
will be automatically moved to the end of the last read character.
Write to a File
The file write operations can be performed by the functions fprintf() and fputs() with
similarities to read operations. C programming also provides some other functions that can be
used to write data to a file such as:
Function Description
fprintf( Similar to printf(), this function use formatted string and varible arguments list to print
) output to the file.
fputs() Prints the whole line in the file and a newline at the end.
fwrite() This functions write the specified amount of bytes to the binary file.
Example:
FILE *fptr ;
fptr = fopen(“fileName.txt”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);
Closing a File
The fclose() function is used to close the file. After successful file operations, you must always
close a file to remove it from the memory.
Syntax of fclose()
fclose(file_pointer);
Example:
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fptr);
Example 1: Program to Create a File, Write in it, And Close the File
C
#include <stdio.h>
#include <string.h>
int main()
FILE* filePointer;
if (filePointer == NULL) {
else {
printf("The file is now opened.\n");
if (strlen(dataToBeWritten) > 0) {
fputs(dataToBeWritten, filePointer);
fputs("\n", filePointer);
fclose(filePointer);
"GfgTest.c\n");
return 0;
Output
This program will create a file named GfgTest.c in the same directory as the source file which
will contain the following text: “GeeksforGeeks-A Computer Science Portal for Geeks”.
Example 2: Program to Open a File, Read from it, And Close the File
C
#include <string.h>
int main()
FILE* filePointer;
// file
char dataToBeRead[50];
if (filePointer == NULL) {
else {
!= NULL) {
// Print the dataToBeRead
printf("%s", dataToBeRead);
fclose(filePointer);
printf(
return 0;
Output
This program reads the text from the file named GfgTest.c which we created in the previous
example and prints it in the console.
Till now, we have only discussed text file operations. The operations on a binary file are
similar to text file operations with little difference.
To open a file in binary mode, we use the rb, rb+, ab, ab+, wb, and wb+ access mode in the
fopen() function. We also use the .bin file extension in the binary filename.
Example
We use fwrite() function to write data to a binary file. The data is written to the binary file in
the from of bits (0’s and 1’s).
Syntax of fwrite()
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *file_pointer);
Parameters:
ptr: pointer to the block of memory to be written.
Return Value:
C
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
};
int main()
int n;
FILE* fptr;
exit(1);
int flag = 0;
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
fptr);
if (!flag) {
else {
fclose(fptr);
return 0;
Output
The fread() function can be used to read data from a binary file in C. The data is read from the
file in the same form as it is stored i.e. binary form.
Syntax of fread()
Parameters:
Return Value:
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
};
int main()
int n;
FILE* fptr;
exit(1);
num.n3);
fclose(fptr);
return 0;
Output
fseek() in C
If we have multiple records inside a file and need to access a particular record that is at a
specific position, so we need to loop through all the records before it to get the record. Doing
this will waste a lot of memory and operational time. To reduce memory consumption and
operational time we can use fseek() which provides an easier way to get to the required data.
fseek() function in C seeks the cursor to the given record in the file.
Example of fseek()
C
#include <stdio.h>
int main()
FILE* fp;
fp = fopen("test.txt", "r");
fseek(fp, 0, SEEK_END);
printf("%ld", ftell(fp));
return 0;
Output
81
rewind() in C
The rewind() function is used to bring the file pointer to the beginning of the file. It can be
used in place of fseek() when you want the file pointer at the start.
Syntax of rewind()
rewind (file_pointer);
Example
C
#include <stdio.h>
int main()
FILE* fptr;
// using rewind()
rewind(fptr);
char buf[50];
printf("%s", buf);
return 0;
Output
The following table lists some more functions that can be used to perform file operations or
assist in performing them.
Functions Description