Sunday, 17 February 2019

What is Array in C?









Before knowing about the initialization and declaration of the array in C, it is important to know and understand why we need an array in C? Suppose, we have to save the details of one, two or ten students in a college, then it is easy to declare 10 variables. But if you have to store more than 100 students details, then it is very hard to think and write about so many variables. But with the help of arrays, we can store the information of many people by declaring only one variable. 


       Data or information in the array is stored in the contiguous memory location. In the array, we can store the same data type information. Now, let's learn how to create an array.


Declaration of an Array in C


Whenever you create an array, you define the name of the array and how many values it is going to store in it. As if you want to store 6 numbers, you can create an array for that. The general form of creating an array in C is given below

Data type     Name of array-variable[Size];

By size, you have to tell how many values you want to store.

For example

int arr[6];

Where 'arr' is the name of the array and 6 shows the size of an array i.e. 6 data values you can store in an array 'arr'. 






Initialization of an array in C


We have learned how to declare an array. Now we will learn how to store the values in an array. I would like to tell you that whenever we declare an array, the location is allocated in memory according to its size and that location is allocated with the same number of index numbers. An index number is a unique name for every location. You should always remember one thing is that the index of the array always starts with zero.

arr[0]
arr[1]
arr[2]
arr[3]
arr[4]
arr[5]

In the declaration of an array, you can insert value in this way,


arr[0] =10;
arr[1] = 67;
arr[2] = 98;
arr[3] = 68;
arr[4] = 34;
arr[5] = 54;

or you can insert value in an array like this,

int arr[6] = {10,67,98,68,34,54};

And if you want to give values during the run time of program then you can put values in this way,

for (i=0; i <= 6; i++)
{
printf ("Enter values in an array");
scanf ("%d", &arr[i]);
}

Accessing array elements 


If we want to access data from the array then 

printf ("Data of array = %d\n", arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]);
  
The values of the array will be printed on the statements given above and if you want to perform an operation you can access their values by writing the direct array name arr[0], arr[1] etc.


And if you want to access the values of the array then you can use the loop,

for (i = 0; i < 6; i++)
{
printf ("%d\n", arr[i]);
}


C program to demonstrate the initialization and accessing of array elements.


#include <stdio.h>
#include <conio.h>
int main( )
{
    //Declaration of an array
    int arr[6]; int i;

    //Initialization of an array
    printf ("Enter array element\n");
    for (i=0; i<6; i++)
    {
        scanf("%d",&arr[i]);
    }

    //Print array element
    for (i=0; i<6; i++)
    {
        printf ("%d\n", arr[i]);
    }
    return 0;
}


Output










How to calculate the size of An array in C


Array in C
Size of an array in C















#include <stdio.h>
int main( )
{
    int arr[5];
    int size, size_of_array, n;

// Determine the size of an array
    size = sizeof (arr);
    printf ("size=%d\n", size);

// Determine the size of an element in an array
     n = sizeof (arr[0]);
     printf ("n=%d\n", n);

// Determine number of elements in an array
    size_of_array = sizeof (arr)/ sizeof (arr[0]);
    printf ("size_of_array=%d\n", size_of_array);

    return 0;
}


Output
size=20
n=4
size_of_array=5


2-dimensional Array  in C


In the 2-dimensional arrays, the data is stored in the form of the table. For example, we want to store roll number of students, their names and their marks, then we will declare them using a 2-dimensional array.


Array in C
2-dimensional array








Declaration of a 2-dimensional array in C


A 2-dimensional array is declared in the form of row and column,

 Data type  name of an array [row][column];


The roll number of students, their name and their marks will be written using this 2-dimensional array

int arr[4][3];

4 rows and 3 columns (the first column is of the roll number of students, second is their name and the third column is of marks as shown in above figure).

Initialization of a 2-dimensional array in C


int arr[4][3] = {1,2,3,4,5,6,7,8,9,10,11,12};

OR

int arr[4][3] ={{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};


In this initialization, the set of each inner braces represents a row. There is a total of 4 rows so there are 4 sets of inner braces.

Accessing 2-dimensional array in C


To access any single element in the 2-dimensional array, write it like this,

#include <stdio.h>
int main ( )
{
    //Declaration and initialization of Two-Dimensional Array
    int arr[4][3] = {101,102,103,104,105,106,107,18,109,10,11,12};

    //Access first element of third row
    printf ("%d\n", arr[3][0]);
return 0;
}

Output
10


To access all the elements of the two-dimensional array, we have to use two loops, one for loop for rows and another for loop for the column. 


#include <stdio.h>
int main ( )
{
    int arr[4][3]= {101,102,103,104,105,106,107,18,109,10,11,12};
    int i,j;

    for (i=0; i<4; i++)     // This loop is for row
    {
        for (j=0;j<3;j++)   // This loop is for column
        {
                printf ("%d\n", arr[i][j]);

        }
    }
return 0;
}

Output

101
102
103
104
105
1006
107
108
109
10
11
12

Pass an array to the function


A program below has been written in which ae are adding values of two arrays, and it has also been shown the way how to pass an array to the function.


#include <stdio.h>

// Declaration of function to add array
int add_array(int arr[ ], int brr[ ], int crr[ ]);

int main ( )
{
    //Declaration of integer i.
    int i;

    //Declaration and initialization of array arr and brr

    int arr[5] = {1,2,3,4,5};
    int brr[5] = {1,2,3,4,5};
    int crr[5];

    add_array(arr,brr,crr); //Calling Function add_array

    for (i=0;i<5;i++)
    {
        printf ("%d\n", crr[i]);
    }
    return 0;
}


int add_array(int arr[5], int brr[5], int crr[5])
{
    int j;
    for (j=0;j<5;j++)
    {
        crr[j]=arr[j]+brr[j];
    }
    return crr;
}


Output
2
4
6
8
10



C program to demonstrate the passing 2-dimensional array to the function  


#include <stdio.h>
#define M 2
#define N 2
int add_2d_array(int a[][N], int b[][N], int c[][N]);
int main ( )
{
    int a[M][N]={1,2,3,4};
    int b[M][N]={1,4,6,7};
    int c[M][N]; int i,j;

    add_2d_array(a,b,c);

    for (i=0;i<M;i++)
    {
        for(j=0;j<N;j++)
        {
            printf ("%d\n", c[i][j]);
        }
    }
    return 0;
}

int add_2d_array(int a[][N], int b[][N], int c[][N])
{
    int i,j;
    for (i=0;i<M;i++)
    {
        for (j=0;j<N;j++)
        {
            c[i][j]=a[i][j]+b[i][j];
        }
    }
    return c;
}


Output
2
6
9
11


Pointer to array


The array is also called a constant pointer. This pointer points to the first element of the array. Whenever you create an array, this pointer automatically created. So, if you assign an array name to a pointer variable, then there is no need to use an address of (&) operator before the name of the array. Because as I mentioned earlier an array name is already a constant pointer.

#include <stdio.h>
int main ( )
{
    // Declaration and initialization of array
    int array[5] = {11,22,33,44,55};
    int *qtr; int i;
    qtr = array;

    // Print 0th element of an array
    printf ("%d\n", *qtr);

 // Print all elements of an array
    for (i=0; i<5; i++)
    {
        printf ("%d\n", *(qtr+i));
    }

    return 0;
}



Output
11
11
22
33
44
55


Pointer to a 2-dimensional array in C


#include <stdio.h>
int main()
{
    // Declaration and initialization of 2-d array in C
    int array[3][2] = {
        {11,22},
        {44,55},
        {77,88}
        };
    int *qtr; int i,j;
    qtr = array;

 // Print all elements of an array
    for (i=0; i<3; i++)
    {
        for (j=0;j<2;j++)
        {
        printf ("%d", *(*(array + i) + j));
        printf ("\n");
        }
    }

    return 0;
}


Output

11
22
44
55
77
88



Recommended Posts

Pointer Pointer
Function pointer in C


















































References
1. Wikipedia
2. Geeksforgeeks






Thursday, 7 February 2019

Pointer Pointer / Pointer to Pointer / Double Pointer

What is a pointer pointer?


When a pointer variable store address of another pointer variable is known as pointer pointer or pointer to pointer or double pointer in C.

Declaration of pointer pointer (double pointer)


int *ptr;


Initialization of pointer pointer (double pointer)

int a = 10;
int *ptr, **q;
ptr =&a;
q = & ptr;  //initialization of pointer variable q

Pointer in C
Types of pointers in C
Dangling Pointer
Function Pointer


C program to demonstrate pointer pointer (double pointer)

#include <stdio.h>
int main ( )
{
int a = 10; //Declaration and initialization of variable
int *ptr; //Declaration of pointer vaiable ptr (ptr is a single pointer)
int **q; // Declaration of  pointer variable q (q is a double pointer)
ptr = &a; // Initialization of pointer variable ptr
q = &ptr; // Initialization of pointer variable q
printf ("value of ptr=%d\n value of q=%d\n", *ptr, **q);
printf ("q=%d", *q);
return 0;
}


Output
value of ptr =10
value of q = 10
q = 2686744

Explanation of above program


int a = 10;


pointer pointer












int *ptr

pointer pointer










int **q;

pointer pointer











ptr = &a;
= &ptr;


pointer pointer











In the above program, variable 'a' hold the value '10'. Pointer variable 'ptr' hold the address of the variable 'a' that is 26869 and pointer variable 'q' hold the address of pointer variable 'ptr' that is 40000.  If we want to access the value of the variable 'a' by pointer variable 'ptr' and 'q' then we using int *ptr and int **q. 


How int  **q; access the value of the variable 'a'?

int **q;

pointer 'q' hold the address of the pointer 'ptr' and pointer 'ptr' hold the address of the variable 'a'.

**q  ==> *(40000) ==> 10 

or 

**q ==> *(address of *ptr) ==> (value of variable 'a' = 10)




Recommended Posts











Sunday, 3 February 2019

Function pointer in C

What is the function pointer in C?

Function pointer in C is similar to a normal pointer. The difference between function pointer in C and in normal pointers is that normal pointers point to the address of data but function pointers point to the address of the function. Function pointer in C is also known as the pointer to function. 


Declaration of function pointer in C

Declaration of function pointer in C similar to function. The only difference is that whenever we declared function pointer we use * before declaration name and enclosed in parenthesis.

Syntax

return type     (*identity)    (argument-list)


For example

int (*p) (int *, int *);

In the above expression, p is a function pointer taking two arguments (int, int) and returns an integer. In the above expression, brackets play a very important role, if we removed brackets then it becomes int *p (int, int), which is the declaration of a function with two integer pointer as arguments and returns integer pointer.

Initialization of function pointer in C

Function pointer in C is initialized similarly to the initialization of normal pointers in C. 

Initialization of normal pointers in C

#include <stdio.h>
int main ()
{
int *p;  // declaration of pointer p
int a =34; // declaration and initialization of variable a
p = &a; // initialization of pointer p
printf ("value =%d\n", *p);
return 0;
}

Initialization of function pointers in C

#include <stdio.h>
#include <stdlib.h>

//function used to add two numbers
int sub(int a, int b)
{
  int c;
  c=a-b;
  return c;
}


int main()
{
 int q= 0;
 //Declaration of function pointer p
 int (*p)(int,int) = NULL;
 //initialization of the function pointer
 p = sub;
 //Calling the function using function pointer
 q = (*p)(50,20);
 printf("\n\n Subtraction of two number = %d\n\n",q);
 return 0;
}


Output
Subtraction of two number = 30








Tuesday, 29 January 2019

Dangling pointer | Causes of Dangling pointer | How to avoid it


A pointer in the C programming language plays a very important role, but if we are not used pointer properly then they create some crucial issues. In this article, we will discuss the bad effect of pointers. Before start discussion on the dangling pointer, let's take a look on, how the pointer is allocated in memory?


Dangling Pointer
Figure 1: Pointer points an allocated memory




















What is Dangling pointer?


A dangling pointer is created when data is deleted from memory but pointer still points to that memory location (as shown in Figure 2). An issue is created because pointer still pointing to the memory which is not available. When the programmer tries to dereference the dangling pointers that it shows undefined behaviour and can be the cause of the segmentation fault. 

A pointer (dangling pointer) which is not pointing to the valid memory location can be the reason of undefined behaviour.



Dangling pointer
Figure 2 Dangling pointer

























In the above figure, pointer x and pointer y pointing to valid memory data but pointer z is pointing to a memory which is deallocated. So, pointer z becomes a dangling pointer. but when you will try to access the pointer z then you will get the undefined error. 



Causes of Dangling pointer


There a lot of reason due to the dangling pointer is created. In this section, we will discuss the causes of a dangling pointer.

1. Out of scope


When a local variable is declared or initialized within a block then memory is allocated to the local variable.  That memory is deleted or freed when it comes out of the block. 

#include <stdio.h>
int main()
{
    int *p;

    //block
    int a =10;
    p = &a;
    }
    {
        printf ("a=%d\n", *p);  //Here, p is a dangling pointer
    }
    return 0;
}

2. De-allocation of memory


In the C programming language, malloc, calloc and realloc library function are allocates memory during run time and free is used to de-allocate memory. Combat combination of malloc, calloc, realloc and free generate the dangling pointer. Whenever the user tries to access the freed memory then you will get the segmentation fault. 


#include <stdio.h>
int main ()
{
    int *p = (int*) malloc (sizeof (int));
    free (p);  //free the allocated memory
    *p = 20 // p is dangling pointer
    p = NULL //No more dangling pointer
    return 0;
}



How to avoid Dangling pointer?


The generation of the dangling pointer is avoided by user or programmer if they use NULL explicitly after freeing the dynamic memory.


#include <stdio.h>
int main ()
{
    int *= (int*) malloc (sizeof (int));
    free (p);  //free the allocated memory
    p = NULL //No more dangling pointer
    return 0;
}


Another factor which creates the dangling pointer is to not return the address of the local variable from the function. This can be solved if we are using the static variable because the lifetime of the static variable is throughout the run of the program.


#include<stdio.h>
int *checkstaticfun( )
{
 static int a = 9;
 return &a;
}
int main ( )
{
int *p = NULL;
p = checkstaticfun( );
 // Now p is Not a dangling pointer as it points to static variable.
printf ("%d",*p);
return 0;




In this article, I tried to clear all the concept related to a dangling pointer, but I would love to know about your views. So, Please write your comment in the comment box.



Recommended Posts


























Thursday, 24 January 2019

Types of pointers in C (Null pointer, wild pointer, void pointer, dangling pointer, double pointer)



Pointers in C are used to the defined the address of another variable of the same data type. For example


int q = 10; //declaration and initialization of variable


Types of pointers in C













int *p;       // declaration of pointer variable



Types of pointers in C












p = &q    // initialization of pointer variable 'p'


types of pointers in C












Pointer variable 'p' holds the address of 'q' that is 2000. To access the value of the variable 'q', use *p (asterisk p).  For detailed knowledge: Pointers in C


Types of pointers in C


NULL pointer


  • If we do not want to assign the address of another variable to pointer variable then we use a NULL pointer.
  • A NULL pointer is a predefined macro and its value is 0. 
  • In int *p = NULL; statement, p is an integer type pointer variable which is initialized with NULL and known as a NULL pointer.


A program which prints the value of NUll and NULL pointer.


#include <stdio.h>


int main (  )

{

    int *p = NULL; //declaration and initialization of NULL pointer



    printf ("value of NULL = %d\n\n", NULL);

    
    printf ("value of NULL pointer = %u", p);
    return 0;

}


Output

value of null = 0
value of NULL pointer = 0


Wild pointer


  • Those pointer variables which are declared but not initialized with any address is known as a wild pointer. These pointer variables contain garbage value. 
  • Difference between null pointer and the wild pointer is that null pointer is initialized with zero whereas, a wild pointer is uninitialized and consist garbage value. 

For example

#include <stdio.h>
int main ( )
{
    int *a; //wild pointer
    
    int b = 10;
    
    // After initialization pointer is not a valid pointer
    a = &b; 
    return 0;
}


Void pointer in C

  • A void pointer is an untyped pointer i.e. those pointers which are the point to any variable of any data type. 
  • A void pointer is also known as the generic pointer and general purpose pointer because it can store the address of any type of data. 
  • Declaration of void pointer is similar to normal pointer only difference is that void keyword is instead of data type (int, float, char). for example Void *p;


  • Dereferencing a void pointer in C
Accessing the value of that address which is stored in the pointer variable is called dereferencing. We need a type-casting because the void pointer is not associated with any data type. 


#include <stdio.h>
int main ( )
{
    void *p;
    int q =10;
    p = &q;
    printf ("*p =%d\n", *p);
    return 0;
}

Output

When we will compile above code then we will get an error because in the above tried to dereference the void pointer without type-casting.


Type-cast  the void pointer

#include<stdio.h>

void main ( )
{
int w=41;
float x=49.5;
char y='a';
void *p;


// *((int*)p)) is type-casting of pointer variables
p=&w;
printf ("%d\n",*((int*)p));

p=&x;
printf ("%f\n",*((float*)p));

p=&y;
printf ("%c\n",*((char*)p));

}


Output

41
49.500000
a


Recommended Posts



Monday, 21 January 2019

Pointers in C

INTRODUCTION OF POINTERS IN C



A pointer is a variable in the C programming language which holds the address of another variable of the same data type. For example, an integer variable contains an integer value, however, an integer pointer holds the address of integer variable. Pointers in C have derived data types. Whenever a variable is declared or initialized in the C programming language, memory is allocated to that variable which stores the value of that variable. We can easily see the address of that variable by using the symbol '&'.


Below we have written a program in which we see the address of the variable.

#include <stdio.h>
int main ( )
{
int a = 12;
printf ("Value of a=%d\n", a);
printf ("Address of a=%x\n", &a);
return 0;
}


Output

Value of a =12
Address of a = 28ff1c


Whenever we declared a variable in the C programming language then memory is allocated to that variable. This memory location has its own address, which we just saw above. Assume that system allocated memory location 5698 for a variable 'i'.

int i = 12;


Pointers in C












The computer has to assign 5698 memory location to store the value '12'. 5698 is not only a number, because some other time the computer may choose a different location for storing the value '12'. The variable which holds the address is known as pointer variables. 



A pointer variable holds the address of another variable of same data type and the value of pointer variable gets stored in the memory location.



Declaration and Initialization of Pointers in C


Declaration of pointer variables

Syntax:        data type  *pointer_name;

For example

int *w;
float *x;
char *y;

In int *w, w is an integer data type pointer variable. Similarly, the statement float *x and char *y. Due to the declaration, the compiler allocates memory to the pointer variables w, x and y. Because no value is assigned to these locations, so it contains a garbage value and therefore they point to unknown locations as shown:


int *z; 


Pointers in C













Initialization of pointer variables


When the address of a variable is assigned to a pointer variable then this process is known as initialization. All uninitialized pointers contain some garbage values that will be interpreted as memory addresses. These addresses are not valid or point to some wrong values and the compiler is unable to detect these errors, the program with an uninitialized pointer will give wrong results. So, it is important to initialize variables in the program very carefully.



int   q             // Variable declaration


Pointers in C










Memory address 2000 is allocated to variable q which consist of a garbage value.


int   *p           // Pointer variable declaration


Pointers in C









p = &q;           // Initialization of pointer variable



Pointers in C












After initialization, pointer variable p holds the address of the variable q which is 2000.

We can also combine the initialization with the declaration. 
int *p = q;


How to access a variable through the pointer variable?


Once an address of a variable is assigned to a pointer, the question arises that how to access the value of the variable using the pointer? This is done by using a unary operator (*) asterisk. This is also known as indirection operator or dereferencing operator.

#include <stdio.h>
int main ( )
{
    // Declaring variable and pointer variable
    int a, *q;

    // Initialize variable a
    a = 12;

    // Initialize pointer variable q
    q = &a;

    printf ("%d\n", *q);          //This will print the value of a
    printf ("%d\n", *&a);     // This will print the value of a
    printf ("%d\n", &a);     // This will print the address of a
    printf ("%d\n", p);       // This will print the address of a
    printf ("%d\n", &p);   // This will print the address of p


    return 0;

}