C Programming: Arrays, Pointers and Functions

In today’s video tutorial lets learn more about arrays and pointers, and how we can use them with functions.

Note:
This video tutorial is very important, so please make sure to watch the video till the end and make some notes. These are the basic concepts of arrays, pointers and functions. If you miss this, you’ll find other programs complicated. If you learn these basic concepts thoroughly all the programs related to using points and arrays with function will feel more straightforward. So please watch the video till the end and make note of important things I’m teaching in it. Happy Learning!

Related Read:
Basics of Pointers In C Programming Language
Introduction To Arrays: C Programming Language
Basics of Arrays: C Program
Function / Methods In C Programming Language

Important Topic
Please watch this short video without fail: C Program To Display Elements of Array In Reverse Order using Pointers

Visual Representation

arrays pointers and functions in C

Video Tutorial: C Programming: Arrays, Pointers & Functions


[youtube https://www.youtube.com/watch?v=2wdjJNfP7Hw]

YouTube Link: https://www.youtube.com/watch?v=2wdjJNfP7Hw [Watch the Video In Full Screen.]

Source Code: Simple Pointer Example

#include<stdio.h>
int main()
{
    int num = 5, *ptr;

    ptr = &num;

    printf("Value present at address %d is %d\n", ptr, *ptr);

    return 0;
}

Output:
Value present at address 6356728 is 5

Here we are assigning address of variable num to pointer variable ptr. Using ptr we display the address of num and the value present at that address.

Source Code: Simple Pointer and Array Example

#include<stdio.h>

int main()
{
    int num[5] = {1, 2, 3, 4, 5}, *ptr1, *ptr2;

    ptr1 = &num[0];
    ptr2 = num;

    printf("Base Address using &num[0]: %d\n", ptr1);
    printf("Base Address using num: %d\n", ptr2);

    printf("\n");

    printf("Value at num[0]: %d\n", *ptr1);
    printf("Value at *num: %d\n", *ptr2);
    printf("Value at *(num + 0): %d\n", *(ptr2 + 0));
    printf("Value at index 1: %d\n", *(ptr2 + 1));
    printf("Value at index 2: %d\n", *(ptr2 + 2));

    printf("\n");

    return 0;
}

Output:
Base Address using &num[0]: 6356708
Base Address using num: 6356708

Value at num[0]: 1
Value at *num: 1
Value at *(num + 0): 1
Value at index 1: 2
Value at index 2: 3

Above program proves that both &num[0] and num(array variable name) hold base address of the array. And if you add 1 to base address or any address, it’ll point to the immediately next address of its own type. Since num is of type integer all the addresses will have 4 bytes gap between them – as each address is allocated with 4 bytes of data space.

Important Note

1. Array elements are always stored in contiguous memory location.
2. A pointer when incremented always points to an immediately next location of its own type.
3. Whenever compiler finds num[i] it’ll convert it into *(num + i). Because it’s faster to work with addresses than with variables.

Source Code: Arrays and For Loop

#include<stdio.h>

int main()
{
    int num[5] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < 5; i++)
        printf("%d\n", num[i]);

    printf("\n");

    return 0;
}

Output:
1
2
3
4
5

This is how we access and print array elements – i.e., by using its index as subscript to array name.

Source Code: Address of Array Elements

#include<stdio.h>

int main()
{
    int num[5] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < 5; i++)
        printf("%d\n", num + i); // OR printf("%d\n", &num[i]);

    printf("\n");

    return 0;
}

Output:
6356712
6356716
6356720
6356724
6356728

Since array variable name num holds base address – if we add index value to it, it’ll fetch all the consecutive addresses.

Source Code: Values Associated with Address of Array Elements

#include<stdio.h>

int main()
{
    int num[5] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < 5; i++)
        printf("%d\n", *(num + i));

    printf("\n");

    return 0;
}

Output:
1
2
3
4
5

If we append * infront of a pointer variable it’ll print the value present at that address or memory location.

Note:
If we know the data type of the array and the base address of the array, we can fetch all the remaining addresses and values associated with those addresses.

Source Code: Using num[i] and [i]num Interchangeably

#include<stdio.h>

int main()
{
    int num[5] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < 5; i++)
        printf("%d\n", i[num]);

    printf("\n");

    return 0;
}

Output:
1
2
3
4
5

We can access array elements by adding index value to the base address and appending * to it. i.e., *(num + i). We can write the same thing like this *(i + num) as well. Similarly, we can write num[i] as i[num] too and it outputs the same results.

Source Code: Print Array Elements Using Pointer Variable

#include<stdio.h>
int main()
{
    int num[5] = {1, 2, 3, 4, 5}, i, *ptr;

    ptr = num; // OR ptr = &num[0];

    for(i = 0; i < 5; i++)
        printf("%d\n", *ptr++);

    printf("\n");

    return 0;
}

Output:
1
2
3
4
5

Here we’ve assigned base address to pointer variable ptr. Inside for loop, we print the value present at the current address of ptr and then increment the address by 1 – doing which it points to the next address in the array.

Source Code: Print Array Elements In Reverse Order Using Pointer Variable

#include<stdio.h>

#define N 5

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i, *ptr;

    ptr = &num[N - 1]; // OR ptr = num;

    for(i = 0; i < N; i++)
        printf("%d\n", *ptr--);

    printf("\n");

    return 0;
}

Output:
5
4
3
2
1

Here we are assigning last index elements address to the pointer variable. Inside for loop we print the value present at address ptr and then decrement the value of ptr by 1 for each iteration of for loop – doing which it points to the previous address in the array.

Source Code: Arrays, Pointers & Functions: Call By Value

#include<stdio.h>

#define N 5

void display(int x)
{
    printf("%d\n", x);
}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < N; i++)
       display(num[i]);

    return 0;
}

Output:
1
2
3
4
5

Inside for loop we are passing value/element of array to display() method one by one for each iteration. And inside display() method we’re printing the values. This is called Call by value method.

Source Code: Arrays, Pointers & Functions: Call By Reference

#include<stdio.h>

#define N 5

void display(int *x)
{
    printf("%d\n", *x);
}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < N; i++)
       display(&num[i]);

    return 0;
}

Output:
1
2
3
4
5

Inside for loop we are passing address of each element of array to display() method one by one for each iteration. Since we are passing address to display method, we need to have a pointer variable to receive it. Inside display() method we display the value present at the address being passed.

Source Code: Arrays, Pointers & Functions: Printing address of array elements

#include<stdio.h>

#define N 5

void display(int *x)
{
    printf("%d\n", x);
}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < N; i++)
       display(&num[i]);

    return 0;
}

Output:
6356712
6356716
6356720
6356724
6356728

Inside display() method we’re accepting address using pointer variable, and then printing the addresses to the console window. If we want to print the elements present at the address, we need to append * in front of the pointer variable i.e., *x

Source Code: Add 1 to all the elements of array, using pointers and function

#include<stdio.h>

#define N 5

void oneplus(int *x)
{
    *x = *x + 1;
}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < N; i++)
       oneplus(&num[i]);

    printf("\nArray elements after Oneplus operation!\n");
    for(i = 0; i < N; i++)
       printf("%d\n", num[i]);

    return 0;
}

Output:
Array elements after Oneplus operation!
2
3
4
5
6

Here we are passing address of each element to oneplus() method and inside oneplus() method we’re adding 1 to the value present at the address. We’re printing modified array element values inside main() method.

Source Code: Square all the elements of array – use pointers and function

#include<stdio.h>

#define N 5

void oneplus(int *x)
{
    *x = (*x) * (*x);
}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < N; i++)
       oneplus(&num[i]);

    printf("\nArray elements after Oneplus operation!\n");
    for(i = 0; i < N; i++)
       printf("%d\n", num[i]);

    return 0;
}

Output:
Array elements after Oneplus operation!
1
4
9
16
25

Here we are passing address of each element to oneplus() method and inside oneplus() method we square the value present at the address. We’re printing modified array element values inside main() method.

Source Code: Arrays are pointers in disguise!

#include<stdio.h>

#define N 5

void oneplus5(int x[], int n)
{
    int i;

    for(i = 0 ; i < n; i++)
        x[i] = x[i] + 5;

}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    oneplus5(num, N);

    printf("\nArray elements after oneplus5 operation!\n");
    for(i = 0; i < N; i++)
       printf("%d\n", num[i]);

    return 0;
}

Output:
Array elements after oneplus5 operation!
6
7
8
9
10

Here we are passing base address and the size of array to oneplus5() method. Inside oneplus5() method, we are adding 5 to each element of the array. Once the execution of oneplus5() method completes, control comes back to main() method and here we print all the elements of the array. And the modifications made inside oneplus5() method reflects in main() method when we print the elements of array. Internally, x[i] will be converted into *(x + i) and hence the operation takes place at address level. So the manipulation reflects everywhere in the program.

void oneplus5(int x[], int n)
{
    int i;

    for(i = 0 ; i < n; i++)
        x[i] = x[i] + 5;
}

will be converted to

void oneplus5(int x[], int n)
{
    int i;

    for(i = 0 ; i < n; i++)
        *(x + i) = *(x + i) + 5;
}

Word of Caution!

Whenever you pass base address to a function and operate on the value present at that address, the array element/value gets altered. If you want to avoid it, make sure to pass a duplicate copy of the array to the function and not the base address of the original array.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Introduction To Arrays: C Programming Language

Arrays is one of the most important topics in C programming language. In this video tutorial I’ll give you a brief introduction to Arrays.

Declaring Normal/regular Variable

Syntax:

Data_type variable_name;

Ex: int a;

Declaring Array Variable

Syntax:

Data_type variable_name[array_size];

Ex: int a[5];

Here array variable is a, it can hold upto 5 integer values.

Definition of Array

An array is a collection of data items, of same data type, accessed using a common name.

Important Notes About Arrays In C

1. All the elements inside an array MUST be of same data type.
2. If you try to enter more elements than the size allocated to the array, it’ll start throwing error.
3. If you input less number of elements than the size of array, then remaining memory blocks will be filled with zeros.
4. Array variable name(without index) holds the base address or the address of first element of the array.
5. Previous address plus the size of the data type of the array gives the address of next element in the array.

Related Read:
For Loop In C Programming Language
Basics of Pointers In C Programming Language

Types of Array

There are two types of arrays in c programming:
1. One-dimensional array.
2. Multi-dimensional array.

In today’s tutorial we’ll be learning basics of one-dimensional array.

Since one-dimensional array contains some linear type of data, its also called as list or vector.

Two-dimensional arrays are often referred to as Tables or Matrix.

Video Tutorial: Introduction To Arrays: C Programming Language


[youtube https://www.youtube.com/watch?v=obyIr4dN8K0]

YouTube Link: https://www.youtube.com/watch?v=obyIr4dN8K0 [Watch the Video In Full Screen.]

Source Code: Introduction To Arrays: C Programming Language

Array Read Write: integer type array

#include<stdio.h>

int main()
{
    int a[5], i;

    printf("Enter 5 integers\n");
    for(i = 0; i < 5; i++)
    {
        scanf("%d", &a[i]);
    }

    printf("Array elements are:\n");
    for(i = 0; i < 5; i++)
    {
        printf("%d\n", a[i]);
    }

    return 0;
}

Output:
Enter 5 integers
6
8
5
9
2
Array elements are:
6
8
5
9
2

Declaring and Initializing: integer type array

#include<stdio.h>

int main()
{
    int a[5] = { 4, 5, 1, 9, 2 }, i;

    printf("Array elements are:\n");
    for(i = 0; i < 5; i++)
    {
        printf("%d\n", a[i]);
    }

    return 0;
}

Output:
Array elements are:
4
5
1
9
2

Since a[5] is of type integer, all the array elements must be integers too. we must enclose all the elements inside curly braces and each element must be separated by a comma.

Trying to insert more values than array size

#include<stdio.h>

int main()
{
    int a[5] = { 4, 5, 1, 9, 2, 6 }, i;

    printf("Array elements are:\n");
    for(i = 0; i < 5; i++)
    {
        printf("%d\n", a[i]);
    }

    return 0;
}

Output:
warning: excess elements in array initializer.

In above source code we are trying to insert 6 integer values inside a[5], which can hold only 5 integer numbers. Hence compiler throws error and stops further compilation.

Inserting less elements/values than array size

#include<stdio.h>

int main()
{
    int a[5] = { 4, 5, 1 }, i;

    printf("Array elements are:\n");
    for(i = 0; i < 5; i++)
    {
        printf("%d\n", a[i]);
    }

    return 0;
}

Output:
Array elements are:
4
5
1
0
0

Here array size is 5, but we’re only initializing 3 integer values. So rest of it will be filled with zeros.

To avoid conflict between number of elements and array size

#include<stdio.h>

int main()
{
    int a[] = { 4, 5, 2, 6, 1, 2, 4, 5 }, i;

    printf("Array elements are:\n");

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

    return 0;
}

Output:
Array elements are:
4
5
2
6
1
2
4
5

Here we’re not specifying the size of array variable a. Compiler dynamically allocates size to it based on the number of integer numbers assigned to it.

Another method of assigning values to array variable

#include<stdio.h>


int main()
{
    int a[3], i;

    a[0] = 4;
    a[1] = 5;
    a[2] = 9;

    printf("Array elements are:\n");
    for(i = 0; i < 3; i++)
    {
        printf("%d\n", a[i]);
    }

    return 0;
}

Output:
Array elements are:
4
5
9

We could use the index and insert the value at specified position inside an array.

Note: Indexing starts from 0 in C programming language. For example, if you have an array a[5], then the elements are accessed one by one like this: a[0], a[1], a[2], a[3], a[4].

Overwriting value of elements in an array

#include<stdio.h>

int main()
{
    int a[] = { 4, 5, 2, 6, 1, 2, 4, 5 }, i;

    a[5] = 100;

    printf("Array elements are:\n");

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

    return 0;
}

Output:
Array elements are:
4
5
2
6
1
100
4
5

Here previous value of a[5], which is 2 will be replaced by 100.

Pointers and Arrays

#include<stdio.h>

int main()
{
    int a[5] = { 4, 5, 2, 6, 1 };

    printf("%d\n", a);
    printf("%d\n", &a[0]);

    return 0;
}

Output:
6356716
6356716

Here variable a will have base address or the address of first array element. In above program we’re printing the value of a and also the address where the first element of the array is stored. Both display the same address, meaning: a has base address or the address of first element in the array.

Pointers and Arrays

#include<stdio.h>

int main()
{
    int a[5] = { 4, 5, 2, 6, 1 };

    printf("%d\n", &a[0]);
    printf("%d\n", &a[1]);
    printf("%d\n", &a[3]);
    printf("%d\n", &a[4]);

    return 0;
}

Output:
6356716
6356720
6356728
6356732

If you observe above addresses, there is a difference of 4 between each address. That’s because each memory cell stores integer type data(in above program), which is allocated with 4 bytes of memory(it is machine dependent).

Characters and Arrays

#include<stdio.h>

int main()
{
    char ch[5] = { 'A', 'P', 'P', 'L', 'E' };
    int i;

    for(i = 0; i < 5; i++)
        printf("%c", ch[i]);

    return 0;
}

Output:
APPLE

String and Arrays

#include<stdio.h>

int main()
{
    char ch[5] = { 'A', 'P', 'P', 'L', 'E' };

    printf("%s", ch);

    return 0;
}

Output:
APPLE&

Array of characters is called as string. Observe the output of above program. It has ampersand symbol at the end. To remove this kind of random symbols we need to let the program know the end of a string.

#include<stdio.h>

int main()
{
    char ch[6] = { 'A', 'P', 'P', 'L', 'E', '\0' };

    printf("%s", ch);

    return 0;
}

Output:
APPLE

Look at the last element in the array. Its forward slash followed by zero. That indicates end of string.

#include<stdio.h>

int main()
{
    char ch[] = { 'I', 'B', 'M', '\0' };

    printf("%s", ch);

    return 0;
}

Output:
IBM

#include<stdio.h>

int main()
{
    char ch[] = { 'I', 'B', 'M', '\0' };

    printf("%d\n", &ch[0]);
    printf("%d\n", &ch[1]);
    printf("%d\n", &ch[2]);

    return 0;
}

Output:
6356732
6356733
6356734

Character type data has 1 byte of allocated memory. Since this array stores characters in each cell, the address of consecutive element is 1 byte apart.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert