Arrays of Pointers in C Programming

Arrays of Pointers in C Programming

Array of pointers in C programming language can be declared like an array of integers or character. An array of pointers is a collection of pointer variables stored in continuous memory location. In other works, it is an array of addresses. Each element of a pointer array is bound to store address of same data type. Here is the syntax of declaring an array of pointers.

data_type *identifier[size];

For Example

int *array_ptr[100];

Array ‘array_ptr’ is an array of pointer of size 100, where each array element can store the address of integer variable. All array arithmetic holds good with array or pointers also. Here is an example of array of integer pointers.

C Program to show the use of Array of Pointers

Arrays of Pointers in C Programming

#include <stdio.h>
#include <conio.h>
 
void main() {
    int *ptr_array[6];
    int a1=1, a2=2, a3=3 ,a4=4, i;
    int int_array[] = {10, 20};    
 
    /* Assigning addresses of individual variables */
    ptr_array[0] = &a1;
    ptr_array[1] = &a2;
    ptr_array[2] = &a3;
    ptr_array[3] = &a4;
     
    /* Assigning addresses of integer array elements */
    ptr_array[4] = &int_array[0];
    ptr_array[5] = &int_array[1];
     
    /* Printing the integer values in addresses stored in ptr_array*/
 for(i=0; i<6; i++) {
        printf("%d\n", *(ptr_array[i]));
    }
     
    getch();
    return 0;
}

Output

1 
2 
3 
4 
10 
20

C program to print exponentially increase star pattern

  • Write a program in C to print right triangle star (*) pattern of n rows using for loop.
  • Write a C program to print a right angles triangle pattern of star (*) character using loops.

For a exponentially increasing star pattern. Program’s output should be:

Exponential_Star_Pattern

Required Knowledge

Algorithm to print exponentially increasing star pattern using loop

  • Take the number of rows(N) of right triangle as input from user using scanf function.
  • Number of stars in Kth row is equal to 2K. 0th row contains 1 star, 1st row contains 2 stars, 3rd row contains 3 stars. In general, Kth row contains 2K stars.
  • We will use two for loops to print exponential star pattern.
    • For a exponentially increasing star pattern of N rows, outer for loop will iterate N time. Each iteration of outer loop will print one row of the pattern.
    • For Kth row of pattern, inner loop will iterate 2k times. Each iteration of inner loop will print one star (*).

Here is the matrix representation of the exponentially increasing star pattern. The row numbers are represented by i whereas column numbers are represented by j.
Exponential_Star_Pattern

C program to print exponentially increasing star pattern

C program to print exponentially increase star pattern

#include<stdio.h> 
#include<math.h>
 
int main(){
    int i,j,rows;
    printf("Enter the number of rows\n");
    scanf("%d", &rows);
     
    for(i = 0; i < rows; i++){
     /* Prints one row of pattern */
       for(j = 0; j < pow(2,i); j++){
           printf("*");
       }
       /* move to next row */
       printf("\n");
    }
    return 0;
}

Output

Enter the number of rows
4
*
**
****
********
****************

Accessing Members of Structure in C

Accessing Members of Structure in C

We cannot access members of a structure directly in any expression by specifying their name alone.

There are two ways to access structure members

Using Member Access Operator(.) or Dot Operator

structure_variable.member_name

For Example
We can access the member age of employee structure variable employee_one as:

struct employee
{
    char name[100];
    int age;
    float salary;
    char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};

int age = employee_one.age;

Using Member Structure Pointer Operator or Arrow Operator(->)

Structure pointer operator or Arrow operator is used to access members of structure using pointer variable. When we have pointer to a structure variable, then we can access member variable by using pointer variable followed by an arrow operator and then the name of the member variable.

structure_pointer->member_name;
For Example
struct employee
{
    char name[100];
 int age;
 float salary;
 char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};

struct employee *ptr = &employee_one;
int age = ptr->age;

C Program to print the members of a structure using dot and arrow operators

Accessing Members of Structure in C

#include <stdio.h>
#include <conio.h>
 
struct employee {
    char name[100];
 int age;
 float salary;
 char department[50];
};
 
int main(){
   struct employee employee_one, *ptr;
    
   printf("Enter Name, Age, Salary and Department of Employee\n");
   scanf("%s %d %f %s", &employee_one.name, &employee_one.age,
       &employee_one.salary, &employee_one.department);
 
   /* Printing structure members using dot operator */
   printf("Employee Details\n");
   printf(" Name : %s\n Age : %d\n Salary = %f\n Dept : %s\n", 
       employee_one.name, employee_one.age, employee_one.salary,
       employee_one.department);
        
   /* Printing structure members using arrow operator */
   ptr = &employee_one;
   printf("\nEmployee Details\n");
   printf(" Name : %s\n Age : %d\n Salary = %f\n Dept : %s\n", 
       ptr->name, ptr->age, ptr->salary, ptr->department);
 
   getch();
   return 0;
}

Output

Enter Name, Age, Salary and Department of Employee
Jack 30 1234.5 Sales
Employee Details
 Name : Jack
 Age : 30
 Salary = 1234.500000
 Dept : Sales
 
Employee Details
 Name : Jack
 Age : 30
 Salary = 1234.500000
 Dept : Sales

C Data Types

C Program to Show Size of Basic Data Types

data type in C programming language declares the type of data that a variable can store and how much memory is required to store this data. The data type also defines the format in which a data of particular type should be stored.
For Example

  • character
  • integer etc.

C Data types can be classified into four categories

  • Basic Data types : There are four basic data types in C(int, char, float and double.)
  • Derived Data Type : Data types that are derived from fundamental data types are called derived data types(Array, Structures, Unions and Pointers).
  • Void Data Type : Void is an empty data type that has no associated value(void).
  • Enumerated Data Type : Enumeration data type consists of set of named constant values(enum).

C Basic Data Types

There are four basic data types in C programming language.

  • Character  (char)
  • Integer  (int)
  • Floating Point  (float)
  • Double Floating Point  (double)

All other data types are derived from these basic data types.

The size of basic data types are machine dependent, For example size of an integer data type in a 32 bit computer is 4 bytes whereas size of integer data type in 16 bit computer is 2 bytes. To know the exact size of any data type, we should use sizeof operator.

C Data Type Modifiers

Modifiers in C specifies the amount of memory space to be allocated for a variable. Modifiers are prefixed with basic data types to modify the amount of memory allocated for a variable.

For Example in a 16 bit system, the size of int data type is 2 bytes. If we add long prefix in integer variable declaration(long int), it’s size becomes 8 bytes.
There are five data type modifiers in C Programming Language:

  • long
  • short
  • signed
  • unsigned
  • long long

Here, we will discuss about Basic Data types only. We will cover other data types in upcoming tutorials.

The following table, shows the different basic data types, their size and value range in a 16 bit operating system.

Data Types Memory Size in bytes Min-Max Range
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 32,767
signed int 2 bytes -32,768 to 32,767
short int 2 bytes -32,768 to 32,767
unsigned short int 2 bytes 0 to 32,767
signed short int 2 bytes -32,768 to 32,767
long int 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long int 4 bytes 0 to 4,294,967,295
signed long int 4 bytes –2,147,483,647 to 2,147,483,647
char 1 byte -128 to 127
unsigned char 1 byte 0 to 127
signed char 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
signed short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 32,767
float 4 bytes 1E–37 to 1E+37 with six digits of precision
double 8 bytes 1E–37 to 1E+37 with ten digits of precision
long double 10 bytes 1E–37 to 1E+37 with ten digits of precision

C Character Data Type

Character data type is used to store a character. A variable of character data type allocated only one byte of memory and can store only one character. Keyword char is used to declare variables of type character. Range of character(char) data type is -128 to 127.

For Example

char c = ‘A’;
Above statement declares a variable ‘c’ of character data type and stores character ‘A’ in it’s memory location.

Character Data Type Variations

  • char
  • unsigned char
  • signed char

C Integer Data Type

Integer data type is used to store a value of numeric type. Memory size of a variable of integer data type is dependent on Operating System, For example size of an integer data type in a 32 bit computer is 4 bytes whereas size of integer data type in 16 bit computer is 2 bytes.

Keyword int is used to declare variables of type integer. Range of integer(int) data type in 16 Bit system is -32,768 to 32,767.

For Example

int i = 2015;
Above statement declares a variable ‘i’ of integer data type and stores 2015 in it’s memory location.

Integer Data Type Variations

  • int
  • unsigned int
  • signed int
  • short int
  • unsigned short int
  • signed short int
  • long int
  • unsigned long int
  • signed long int

C Floating Point Data Type

Floating point data type can be sub-divided into two types on the basis of precision and size.

float 4 bytes with six digits of precision
double 8 bytes with ten digits of precision

float data type
Floating point data type in C is used to store a value of decimal values. Memory size of a variable of floating point data type is dependent on Operating System, For example size of an floating point data type in a 16 bit computer is 4 bytes. Keyword float is used to declare variables of floating point type. Floating point data type provides up-to 6 digits of precision.

For Example

float f = 11.243567;
Above statement declares a variable ‘f’ of float data type and stores 11.243567 in it’s memory location.
double data type
Floating point data type similar to float data type except it provides up-to ten digit of precision and occupies eight bytes of memory.

For Example

double d = 11676.2435676542;
Above statement declares a variable ‘d’ of double data type and stores 11676.2435676542 in it’s memory location.

C Program to Show Size of Basic Data Types

C Program to Show Size of Basic Data Types

#include <stdio.h>
#include <conio.h>
#include <limits.h>
 
int main(){
   /* 
    * Size of Data type is dependent on Operating System
    * I am running this program in a 32 bit OS 
    */
   printf("Size for char : %d \n", sizeof(char));
   printf("Size for int : %d \n", sizeof(int));
   printf("Size for float : %d \n", sizeof(float));
   printf("Size for double : %d \n", sizeof(double));
    
   getch();
   return 0;
}

Output

Size for char : 1
Size for int : 4
Size for float : 4
Size for double : 8

C Program to Swap Major and Minor Diagonals of a Matrix

  • Write a C program to swap major diagonal and minor diagonal of a square matrix.
  • WAP to interchange diagonal elements of a square matrix.

Required Knowledge

This program takes a square matrix as input from user and swaps the element of major and minor diagonals.
For Example:

Input Matrix
1 2 3
4 5 6
7 8 9
Output Matrix
3 2 1
4 5 6
9 8 7

Algorithm to swap major and minor diagonal elements of a square matrix
Let inputMatrix is a square matrix of row and column dimension N.

  • For every row, we will swap the elements of major and minor diagonals.
  • In any row R, the major diagonal element will be at inputMatrix[R][R] and minor diagonal element will be at inputMatrix[R][COLS-R-1] where COLS is the total number of columns in square matrix inputMatrix.

C program to sort an array in increasing order using bubble sort

C Program to Swap Major and Minor Diagonals of a Matrix

/*
* C Program to interchange Major and Minor diagonals of a Matrix
*/
  
#include <stdio.h>
#include <conio.h>
  
int main(){
    int rows, cols, row, col, temp;
    int matrix[50][50];
     
    printf("Enter Rows and Columns of Square Matrix\n");
    scanf("%d %d", &rows, &cols);
      
    printf("Enter Matrix of size %dX%d\n", rows, cols);
      
    for(row = 0; row < rows; row++){
        for(col = 0; col < cols; col++){
            scanf("%d", &matrix[row][col]);
        }
    }
      
    /* Interchange Major and Minor diagonals of Matrix */
    for(row = 0; row < rows; row++) {  
        col = row;    
        temp = matrix[row][col];  
        matrix[row][col] = matrix[row][(cols-col)-1];  
        matrix[row][(cols-col)-1] = temp;  
    }  
      
    printf("Matrix After Swapping Diagonals\n");
    for(row = 0; row < rows; row++){
        for(col = 0; col < cols; col++){
            printf("%d ", matrix[row][col]);
        }
        printf("\n");
    }
     
    getch();
    return 0;
}

Output

Enter Rows and Columns of Square Matrix
3 3
Enter Matrix of size 3X3
1 2 3
4 5 6
7 8 9
Matrix After Swapping Diagonals
3 2 1
4 5 6
9 8 7

C program to print Hello World without using semicolon

  • Write a program in C to print hello world without using semicolon and using if-else statement.
  • How to print Hello World using switch case statement.

In below programs, we will try to print “Hello World” string without using semicolon.

C program to print Hello World string using if statement

#include<stdio.h>
 
int main(){
    if(printf("Hello World")){
    }
}

Output

Hello World

C program to print Hello World without using semicolon and using switch statement

Here, we are using switch case statement to print “Hello World”. Remember, it is not compulsory to use case statement inside switch, a switch statement without any case value is a valid statement. Check this tutorial on switch statement.

#include<stdio.h>
 
int main(){
    switch(printf("Hello World")){
    }
}

Output

Hello World

C program to print Hello World without using semicolon and using if-else statement

A print statement always returns the number of characters printed on screen. Hence, !printf(“Hello “) will always return a false value which will force evaluation of else-if condition.

C Program to Print Days of Week in Words using Switch Case Statement

  • Write a C program to print name of days of week using switch case statement.

Required Knowledge

We will take a number between 1 to 7 as input from user, where 1 corresponds to Monday, 2 corresponds to Tuesday and so on. We will use switch case statement to print name of day in words.

C program to print name of day using switch case statement

C program to print name of day using switch case statement

#include <stdio.h> 
   
int main() {  
    int day;
    /* 
     * Take the Day number as input form user  
     */ 
    printf("Enter Day Number (1 = Monday ..... 7 = Sunday)\n");  
    scanf("%d", &day);  _
  
    switch(day){
        case 1 : printf("Monday\n");
            break;
        case 2 : printf("Tuesday\n");
            break;
        case 3 : printf("Wednesday\n");
            break;
        case 4 : printf("Thursday\n");
            break;
        case 5 : printf("Friday\n");
            break;
        case 6 : printf("Saturday\n");
            break;
        case 7 : printf("Sunday\n");
            break;
        default: printf("Invalid Input !!!!\n");          
    }
  
    return 0;  
}

Output

Enter Day Number (1 = Monday ..... 7 = Sunday)
4
Thursday
Enter Day Number (1 = Monday ..... 7 = Sunday)
7
Sunday
Enter Day Number (1 = Monday ..... 7 = Sunday)
12
Invalid Input !!!!

C Program to Reverse an Array Using Recursion

To Reverse an array we have to reverse the sequence of array elements. The first element of array should become the last element and last element will become the first element.

For Example:
If Input array is : 1 2 3 4 5 6 7
Reversed array should be : 7 6 5 4 3 2 1

To reverse an array of length N using recursion, we have to swap the leftmost(array[0]) and rightmost(array[N-1]) element of array and then recursively reverse the inner sub-array from index 1 to N-2. Keep on repeating this unless size of sub-array is greater than one.

Algorithm to reverse an array using recursion
Let inputArray is an array of length N and leftIndex and rightIndex are two integer variables to store index references

  • We can use recursion to reverse an array by creating a smaller sub-problem from original problem.
  • To reverse an array, we will first swap first element(inputArray[0]) and last element(inputArray[N-1]) of array and then recursively reverse subarray from index 1 to N-2.
  • Let reverse is a function with takes array, leftIndex and rightIndex as input. It first swap inputArray[leftIndex] and inputArray[rightIndex] and then recursively call itself on sub array from index leftIndex+1 to rightIndex-1.
  • void reverse(int *array, int leftIndex, int rightIndex);
  • reverse(inputArray, i, j) = swap(inputArray[i], inputArray[j]) and reverse(inputArray, i+1, j-1).
  • Recursion will break when leftIndex becomes >= rightIndex.

C program to reverse and array using recursion

Below program uses two user defined functions ‘swap’ and ‘reverse’. Function swap(int *array, int leftIndex, int rightIndex) swaps the elements of array at index leftIndex and rightIndex whereas function reverse(int *array, int leftIndex, int rightIndex) is a recursive function that reverse the sub array of array from index leftIndex to rightIndex.

Reverse function internally calls swap function to swap leftmost and rightmost element of subarray and then all itself to reverse sub-array excluding leftmost and rightmost element. Recursion will terminate when leftIndex becomes greater than or equal to rightIndex, or in other words when size of the sub-array becomes less than or equal to 1.

C Program to Reverse an Array Using Recursion

/*
* C Program to reverse an array using recursion
*/
#include <stdio.h>
#include <conio.h>
 
void swap(int *array, int leftIndex, int rightIndex);
void reverse(int *array, int leftIndex, int rightIndex);
 
int main(){
    int inputArray[500], elementCount, counter;
     
    printf("Enter number of elements in array: ");
    scanf("%d", &elementCount);
    printf("Enter %d numbers \n", elementCount);
     
    for(counter = 0; counter < elementCount; counter++){
        scanf("%d", &inputArray[counter]);
    }
     
    reverse(inputArray, 0, elementCount - 1);
     
    /* Print Reversed array */
    printf("Reversed Array\n");
    for(counter = 0; counter < elementCount; counter++){
        printf("%d ", inputArray[counter]);
    }
         
    getch();
    return 0;
}
/*
*  Function to swap two numbers in array
*/
void swap(int *array, int leftIndex, int rightIndex){
   int temp;
   temp = array[leftIndex];
   array[leftIndex] = array[rightIndex];
   array[rightIndex] = temp;
}
 
/*
* Function to reverse an Array using recursion 
*/
void reverse(int *array, int leftIndex, int rightIndex){
    if(NULL == array){
        printf("Invalid Input");
        return;
    }
    /*
    * Swap left and right elements and recursively call reverse 
    * function on subArray [leftIndex + 1, rightIndex - 1] 
    */
    if(leftIndex < rightIndex){
        swap(array, leftIndex, rightIndex);
        reverse(array, leftIndex+1, rightIndex-1);
    }
}

Program Output

Enter number of elements in array: 6
Enter 6 numbers 
1 2 3 4 5 6
Reversed Array
6 5 4 3 2 1

C Program to Swap Two Numbers

C Program to Swap Two Numbers
  • Write a program in c to swap two numbers.
  • How to swat the two variables without using temporary variable.

Swapping two numbers means interchanging the values of two variables.
For Example
Before swapping
A = 3, B = 4
After swapping
A = 4, B = 3

We have to take two numbers as input from user and stores them in two integer variables. There are various ways of swapping values like using a temporary variable, using XOR bitwise operator and without using any temporary variable. Here we will discuss about various ways of swapping and their pros and cons.

C program to swap two numbers using third variable

This program uses a third variable temp of type int. We will use this variable to temporarily store the value of first number. Then we copy second variable in to first variable. As we have saved the value of first variable in temp, we can reassign it not to second variable.

This is the safest way to swap two variables.

C Program to Swap Two Numbers

/*
* C Program to swap two numbers
*/
#include <stdio.h>
#include <conio.h>
 
int main(){
    int firstNumber, secondNumber, temp;
    printf("Enter two numbers \n");
    scanf("%d %d", &firstNumber, &secondNumber);
    printf("First Number: %d\nSecond Number: %d\n", 
        firstNumber, secondNumber);   
         
    /* Swap firstNumber and secondNumber using a third variable */
    temp = firstNumber;
    firstNumber = secondNumber;
    secondNumber = temp;
     
    printf("\nAfter Swap\n");
    printf("First Number: %d\nSecond Number: %d\n", 
        firstNumber, secondNumber);
    getch();
    return 0;
}

Program Output

Enter two numbers 
2 5
First Number: 2
Second Number: 5

After Swap
First Number: 5
Second Number: 2

C program to swap two numbers without using temporary variable

We first get the sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum. There is one problem in this approach, the sum of both numbers may overflow the range of integer, in that case we will get wrong values.

C program to swap two numbers without using temporary variable

/*
* C Program to swap two numbers without using third variable 
*/
#include <stdio.h>
#include <conio.h>
 
int main(){
    int firstNumber, secondNumber;
    printf("Enter two numbers \n");
    scanf("%d %d", &firstNumber, &secondNumber);
    printf("First Number: %d\nSecond Number: %d\n", 
        firstNumber, secondNumber);
        
    /* Swap firstNumber and secondNumber without using
       a third variable */
    firstNumber = firstNumber + secondNumber;
    secondNumber = firstNumber - secondNumber;
    firstNumber = firstNumber - secondNumber;
     
    printf("\nAfter Swap\n");
    printf("First Number: %d\nSecond Number: %d\n", 
         firstNumber, secondNumber);
     
    getch();
    return 0;
}

Program Output

Enter two numbers 
5 6
First Number: 5
Second Number: 6

After Swap
First Number: 6
Second Number: 5

C program to swap two numbers using pointers

In this program we are using a user defined function ‘swap’ that takes the address of two numbers and swaps their values using a third pointer variable as temporary buffer. This program swaps the values stored in particular memory locations not the references.

C program to swap two numbers using pointers

/*
* C Program to swap two numbers using pointers
*/
#include <stdio.h>
#include <conio.h>
 
void swap(int *firstNumber, int *secondNumber);
int main(){
    int firstNumber, secondNumber;
    printf("Enter two numbers \n");
    scanf("%d %d", &firstNumber, &secondNumber);
    printf("First Number: %d\nSecond Number: %d\n", firstNumber, secondNumber);   
     
    swap(&firstNumber, &secondNumber);
     
    printf("\nAfter Swap\n");
    printf("First Number: %d\nSecond Number: %d\n", firstNumber, secondNumber);
    getch();
    return 0;
}
 
/*
 * Function to swap two numbers using pointers
 */
void swap(int *firstNumber, int *secondNumber){
   int temp = *firstNumber;
   *firstNumber = *secondNumber;
   *secondNumber = temp;
}

Program Output

Enter two numbers 
2 3
First Number: 2
Second Number: 3

After Swap
First Number: 3
Second Number: 2

C program to swap two numbers using bitwise XOR operator

We can use bitwise XOR operator to swap two variables. The XOR of two numbers x and y returns a number which has all the bits as 1 wherever bits of x and y differ. Now, doing Xor again with any of the variable with return other variable.

C program to swap two numbers using bitwise XOR operator

/*
* C Program to swap two numbers using Xor Operator
*/
#include <stdio.h>
#include <conio.h>
  
int main(){
    int firstNumber, secondNumber;
    printf("Enter two numbers \n");
    scanf("%d %d", &firstNumber, &secondNumber);
    printf("First Number: %d\nSecond Number: %d\n",
        firstNumber, secondNumber);  
    
    firstNumber = firstNumber ^ secondNumber;
    secondNumber = firstNumber ^ secondNumber;
    firstNumber = firstNumber ^ secondNumber;
    
    printf("\nAfter Swap\n");
    printf("First Number: %d\nSecond Number: %d\n",
        firstNumber, secondNumber);
    getch();
    return 0;
}

Functions in C Programming

Functions in C programming language are building blocks of a C program. A function is a sequence of statements to perform a specific task and it can be called by other functions. A function may take some input and perform a logical unit of task and may return the response to calling function.
The function in C language is also known as method, subroutine or procedure.

  • A C program is a set of function calling each other.
  • We can use any number of functions in a C program.
  • All C programs must contains at least one main() function.

Advantage of Functions in C Programming

  • A large C program can divide into set of functions, where each function owns the responsibility of performing one specific task.
  • Splitting a C program into functions, makes it easy to maintain and improves understandability of very large C programs.
  • We can call a function any number of times in a program from any place which avoid rewriting same code again and again at various program.
  • We can add common utility functions in header files, So that It can be reused by other programs.

Functions in Details

Click on the links below to check detailed description of functions in C programming.

  • Function Definition in C
  • Function Declaration(prototype) in C
  • Calling a Function in C
  • Passing Arguments to a Function in C
  • Important Facts about Functions in C

How Functions work in C

  • First of all main() function of C program gets called by Operating system.
  • Execution of C program begins. Program’s statements and expressions getting executed in top to bottom sequence.
  • When control reaches a function call lets say myFunction(int val); it pauses the execution of current function and control goes inside the called function myFunction.
  • Once execution of code inside myFunction body finishes control comes back to the calling function. It resumes the execution of calling function at the next statement following the function call of myFunction.
  • At the point of any function call, control keeps on jumping between calling function and called function.
  • C program terminates when execution of main function ends.