0% found this document useful (0 votes)
198 views

C Notes

An array is a collection of data elements of the same type stored contiguously in memory. Arrays allow for random access of elements via indexes and can store primitive data types like int and char as well as complex data types. C arrays have fixed sizes set at declaration. Functions can accept arrays as arguments and return arrays as well, passing the array name which contains the address of the first element. Arrays provide advantages like code optimization and ease of sorting but have the disadvantage of fixed sizes.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
198 views

C Notes

An array is a collection of data elements of the same type stored contiguously in memory. Arrays allow for random access of elements via indexes and can store primitive data types like int and char as well as complex data types. C arrays have fixed sizes set at declaration. Functions can accept arrays as arguments and return arrays as well, passing the array name which contains the address of the first element. Arrays provide advantages like code optimization and ease of sorting but have the disadvantage of fixed sizes.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

C Array

An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which
can store the primitive type of data such as int, char, double, float, etc. It also has the
capability to store the collection of derived data types, such as pointers, structure, etc.
The array is the simplest data structure where each data element can be randomly
accessed by using its index number.

Properties of Array
The array contains the following properties.
o Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.

Advantage of C Array
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn
later.

Declaration of C Array
We can declare an array in the c language in the following way.
1. data_type array_name[array_size];  
Now, let us see the example to declare the array.

2. int marks[5];  

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.
1. marks[0]=80;//initialization of array  
2. marks[1]=60;  
3. marks[2]=70;  
4. marks[3]=85;  
5. marks[4]=75;  

C array example

1. #include<stdio.h>  
2. int main(){      
3. int i=0;    
4. int marks[5];//declaration of array       
5. marks[0]=80;//initialization of array    
6. marks[1]=60;    
7. marks[2]=70;    
8. marks[3]=85;    
9. marks[4]=75;    
10. //traversal of array    
11. for(i=0;i<5;i++){      
12. printf("%d \n",marks[i]);    
13. }//end of for loop     
14. return 0;  
15. }    

C Array: Declaration with Initialization


We can initialize the c array at the time of declaration. Let's see the code.

1. int marks[5]={20,30,40,50,60};  
In such case, there is no requirement to define the size. So it may also be written as the
following code.

1. int marks[]={20,30,40,50,60};  
2. #include<stdio.h>  
3. int main(){      
4. int i=0;    
5. int marks[5]={20,30,40,50,60};//declaration and initialization of array    
6.  //traversal of array    
7. for(i=0;i<5;i++){      
8. printf("%d \n",marks[i]);    
9. }    
10. return 0;  
11. }    

Two Dimensional Array in C


The two-dimensional array can be defined as an array of arrays. The 2D array is
organized as matrices which can be represented as the collection of rows and
columns. However, 2D arrays are created to implement a relational database lookalike
data structure. It provides ease of holding the bulk of data at once which can be passed
to any number of functions wherever required.

Declaration of two dimensional Array in C


The syntax to declare the 2D array is given below.
1. data_type array_name[rows][columns];  

Consider the following example.

1. int twodimen[4][3];  

Here, 4 is the number of rows, and 3 is the number of columns.

Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D arrays.
We will have to define at least the second dimension of the array. The two-
dimensional array can be declared and defined in the following way.
1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two-dimensional array example in C


1. #include<stdio.h>  
2. int main(){      
3. int i=0,j=0;    
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};     
5. //traversing 2D array    
6. for(i=0;i<4;i++){    
7.  for(j=0;j<3;j++){    
8.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);    
9.  }//end of j    
10. }//end of i    
11. return 0;  

Passing Array to Function in C


In C, there are various general problems which requires passing more than one variable of the
same type to a function. For example, consider a function which sorts the 10 elements in
ascending order. Such a function requires 10 numbers to be passed as the actual parameters
from the main function. Here, instead of declaring 10 different numbers and then passing into
the function, we can declare and initialize an array and pass that into the function. This will
resolve all the complexity since the function will now work for any number of values.
As we know that the array_name contains the address of the first element. Here, we must
notice that we need to pass only the name of the array in the function which is intended to
accept an array. The array defined as the formal parameter will automatically refer to the
array specified by the array name defined as an actual parameter.
Consider the following syntax to pass an array to the function.
1. functionname(arrayname);//passing array  

Methods to declare a function that receives an array as an


argument
There are 3 ways to declare the function which is intended to receive an array as an
argument.
First way:
1. return_type function(type arrayname[])  
Declaring blank subscript notation [] is the widely used technique.
Second way:
1. return_type function(type arrayname[SIZE])  
Optionally, we can define size in subscript notation [].
Third way:
1. return_type function(type *arrayname)  
You can also use the concept of a pointer. In pointer chapter, we will learn about it.

C language passing an array to function example


1. #include<stdio.h>  
2. int minarray(int arr[],int size){    
3. int min=arr[0];    
4. int i=0;    
5. for(i=1;i<size;i++){    
6. if(min>arr[i]){    
7. min=arr[i];    
8. }    
9. }//end of for    
10. return min;    
11. }//end of function    
12.     
13. int main(){      
14. int i=0,min=0;    
15. int numbers[]={4,5,7,3,8,9};//declaration of array    
16.   
17. min=minarray(numbers,6);//passing array with size    
18. printf("minimum number is %d \n",min);    
19. return 0;  
20. }    

Returning array from the function


As we know that, a function can not return more than one value. However, if we try to
write the return statement as return a, b, c; to return three values (a,b,c), the function
will return the last mentioned value which is c in our case. In some problems, we may
need to return multiple values from a function. In such cases, an array is returned from
the function.
Returning an array is similar to passing the array into the function. The name of the
array is returned from the function. To make a function returning an array, the following
syntax is used.
1. int * Function_name() {  
2. //some statements;   
3. return array_type;  
4. }  

C Functions
In c, we can divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}. A function can
be called multiple times to provide reusability and modularity to the C program. In
other words, we can say that the collection of functions creates a program. The
function is also known as procedureor subroutinein other programming languages.

Advantage of functions in C
There are the following advantages of C functions.
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.

Function Aspects
There are three aspects of a C function.
o Function declaration A function must be declared globally in a c program to tell the
compiler about the function name, function parameters, and return type.

o Function call Function can be called from anywhere in the program. The parameter list
must not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.
o Function definition It contains the actual statements which are to be executed. It is the
most important aspect to which the control comes when the function is called. Here,
we must notice that only one value can be returned from the function.

SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list) {function body;}

1. return_type function_name(data_type parameter...){  
2. //code to be executed  
3. }  

Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.

Return Value
A C function may or may not return a value from the function. If you don't have to
return any value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the
function.
Example without return value:
1. void hello(){  
2. printf("hello c");  
3. }  
If you want to return any value from the function, you need to use any data type such
as int, long, char, etc. The return type depends on the value to be returned from the
function.

Example with return value:

1. int get(){  
2. return 10;  
3. }  
In the above example, we have to return 10 as a value, so the return type is int. If you
want to return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the
return type of the method.
1. float get(){  
2. return 10.2;  
3. }  

Different aspects of function calling


A function may or may not accept any argument. It may or may not return any value.
Based on these facts, There are four different aspects of function calls.
o function without arguments and without return value
o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value

Example for Function without argument and return value


Example 1
1. #include<stdio.h>  
2. void printName();  
3. void main ()  
4. {  
5.     printf("Hello ");  
6.     printName();  
7. }  
8. void printName()  
9. {  
10.     printf("Javatpoint");  
11. }  

Example for Function without argument and with return value

Example 1

1. #include<stdio.h>  
2. int sum();  
3. void main()  
4. {  
5.     int result;   
6.     printf("\nGoing to calculate the sum of two numbers:");  
7.     result = sum();  
8.     printf("%d",result);  
9. }  
10. int sum()  
11. {  
12.     int a,b;   
13.     printf("\nEnter two numbers");  
14.     scanf("%d %d",&a,&b);  
15.     return a+b;   
16. }  

Example for Function with argument and without return value


Example 1
1. #include<stdio.h>  
2. void sum(int, int);  
3. void main()  
4. {  
5.     int a,b,result;   
6.     printf("\nGoing to calculate the sum of two numbers:");  
7.     printf("\nEnter two numbers:");  
8.     scanf("%d %d",&a,&b);  
9.     sum(a,b);  
10. }  
11. void sum(int a, int b)  
12. {  
13.     printf("\nThe sum is %d",a+b);      
14. }  

C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common
place called the library. Such functions are used to perform some specific operations.
For example, printf is a library function used to print on the console. The library
functions are created by the designers of compilers. All C standard library functions are
defined inside the different header files saved with the extension .h. We need to
include these header files in our program to make use of the library functions defined in
such header files. For example, To use the library functions such as printf/scanf we
need to include stdio.h in our program which is a header file that contains all the library
functions regarding standard input/output.
The list of mostly used header files is given in the following table.

S Header Description
N file

1 stdio.h This is a standard input/output header file. It contains all the library functions rega
standard input/output.

2 conio.h This is a console input/output header file.

3 string.h It contains all string related library functions like gets(), puts(),etc.

4 stdlib.h This header file contains all the general library functions like malloc(), calloc(), exit(), etc
5 math.h This header file contains all the math operations related functions like sqrt(), pow(), etc.

6 time.h This header file contains all the time-related functions.

7 ctype.h This header file contains all character handling functions.

8 stdarg.h Variable argument functions are defined in this header file.

9 signal.h All the signal handling functions are defined in this header file.

10 setjmp.h This file contains all the jump functions.

C Pointers
The pointer in C language is a variable which stores the address of another variable.
This variable can be of type int, char, array, function, or any other pointer. The size of
the pointer depends on the architecture. However, in 32-bit architecture the size of a
pointer is 2 byte.

Consider the following example to define a pointer which stores the address of an
integer.

1. int n = 10;   
2. int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of t
ype integer.  
Consider the following example to define a pointer which stores the address of an integer.

1. int n = 10;   
2. int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.   

Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
1. int *a;//pointer to int  
2. char *c;//pointer to char  

Pointer Example
An example of using pointers to print the address and value is given below.
1. #include<stdio.h>  
2. int main(){  
3. int number=50;    
4. int *p;      
5. p=&number;//stores the address of number variable    
6. printf("Address of p variable is %x \n",p); // p contains the address of the number there
fore printing p gives the address of number.     
7. printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a p
ointer therefore if we print *p, we will get the value stored at the address contained by 
p.    
8. return 0;  
9. }    

Pointer to array

1. int arr[10];  
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array arr.  

Pointer to a function

1. void show (int);  
2. void(*p)(int) = &display; // Pointer p is pointing to the address of a function  

Pointer to structure
1. struct st {  
2.     int i;  
3.     float f;  
4. }ref;  
5. struct st *p = &ref;  

Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees, etc. and used with arrays, structures, and functions.
2) We can return multiple values from a function using the pointer.
3) It makes you able to access any memory location in the computer's memory.

1) Dynamic memory allocation


In c language, we can dynamically allocate memory using malloc() and calloc()
functions where the pointer is used.
2) Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It reduces
the code and improves the performance.

C Double Pointer (Pointer to Pointer)


As we know that, a pointer is used to store the address of a variable in C. Pointer
reduces the access time of a variable. However, In C, we can also define a pointer to
store the address of another pointer. Such pointer is known as a double pointer
(pointer to pointer). The first pointer is used to store the address of a variable whereas
the second pointer is used to store the address of the first pointer. Let's understand it
by the diagram given below.

The syntax of declaring a double pointer is given below.

1. int **p; // pointer to a pointer which is pointing to an integer.   

Consider the following example.

1. #include<stdio.h>  
2. void main ()  
3. {  
4.     int a = 10;  
5.     int *p;  
6.     int **pp;   
7.     p = &a; // pointer p is pointing to the address of a  
8.     pp = &p; // pointer pp is a double pointer pointing to the address of pointer p  
9.     printf("address of a: %x\n",p); // Address of a will be printed   
10.     printf("address of p: %x\n",pp); // Address of p will be printed  
11.     printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 
10 will be printed  
12.     printf("value stored at pp: %d\n",**pp); // value stored at the address contained by t
he pointer stoyred at pp  
13. }  

Dangling Pointers in C
The most common bugs related to pointers and memory management is dangling/wild
pointers. Sometimes the programmer fails to initialize the pointer with a valid address,
then this type of initialized pointer is known as a dangling pointer in C.

Let's observe the following examples.

In the above figure, we can observe that the Pointer 3 is a dangling pointer. Pointer
1 and Pointer 2 are the pointers that point to the allocated objects, i.e., Object 1 and
Object 2, respectively. Pointer 3 is a dangling pointer as it points to the de-allocated
object.

You might also like