[go: up one dir, main page]

0% found this document useful (0 votes)
12 views19 pages

c unit 4

The document provides an overview of arrays in C programming, detailing their definition, declaration, initialization, and types, including one-dimensional and multi-dimensional arrays. It also covers array access, updating elements, and traversal methods, along with a discussion on pointers in C, their declaration, initialization, and different types. Key concepts include the use of pointers for memory manipulation and various pointer types such as integer pointers, structure pointers, and function pointers.

Uploaded by

ap2.brothers3151
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views19 pages

c unit 4

The document provides an overview of arrays in C programming, detailing their definition, declaration, initialization, and types, including one-dimensional and multi-dimensional arrays. It also covers array access, updating elements, and traversal methods, along with a discussion on pointers in C, their declaration, initialization, and different types. Key concepts include the use of pointers for memory manipulation and various pointer types such as integer pointers, structure pointers, and function pointers.

Uploaded by

ap2.brothers3151
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Unit – 4

Arrays in C Programming
An array is a collection of variables of the same type stored in contiguous memory locations.
Arrays allow you to group related data and perform operations on them efficiently.

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.

1.1 What is an Array?


Definition: A collection of elements (variables) of the same data type, stored in a single
variable. An array in C is a fixed-size collection of similar data items stored in
contiguous memory locations. It can be used to store the collection of primitive data
types such as int, char, float, etc., and also derived and user-defined data types such
as pointers, structures, etc.

 Key Characteristics:
o Elements are stored in contiguous memory locations.
o Each element is accessed using its index (starting at 0).
o Arrays can be single-dimensional, two-dimensional, or multi-dimensional.

1.2 Declaring and Initializing Arrays

Declaration:

Syntax of Array Declaration


data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];
where N is the number of dimensions.

Example:

// C Program to illustrate the array declaration

#include<stdio.h>

#include<conio.h>

void main()

{ clrscr();

// declaring array of integer type

int arr_int[5]= {10,20,30,40,50};

// declaring array of character type

char arr_char[5];

getch();

1.3 Array Initialization with Declaration


In this method, we initialize the array along with its declaration. We use an initializer list to
initialize multiple elements of the array. An initializer list is the list of values enclosed within
braces { } separated b a comma.

data_type array_name [size] = {value1, value2, ... valueN};


1.4 Array Initialization with Declaration without Size
If we initialize an array using an initializer list, we can skip declaring the size of the array as
the compiler can automatically deduce the size of the array in these cases. The size of the
array in these cases is equal to the number of elements present in the initializer list as the
compiler can automatically deduce the size of the array.

data_type array_name[] = {1,2,3,4,5};


The size of the above arrays is 5 which is automatically deduced by the compiler.

1.5 Array Initialization after Declaration (Using Loops)


We initialize the array after the declaration by assigning the initial value to each element
individually. We can use for loop, while loop, or do-while loop to assign the value to each
element of the array.

for (int i = 0; i < N; i++) {


array_name[i] = valuei;
}

// C Program to demonstrate array initialization

#include <stdio.h>

int main()

// array initialization using initialier list

int arr[5] = { 10, 20, 30, 40, 50 };

// array initialization using initializer list without specifying size

int arr1[] = { 1, 2, 3, 4, 5 };
// array initialization using for loop

float arr2[5];

for (int i = 0; i < 5; i++) {

arr2[i] = (float)i * 2.1;

printf("%.2f ", arr2[i]);

return 0;

Hence, You can initialize an array at the time of declaration:

int numbers[5] = {1, 2, 3, 4, 5};

Alternatively, omit the size if the elements are provided:

int numbers[] = {1, 2, 3, 4, 5};

1.6 Array Access Array Elements


We can access any element of an array in C using the array subscript operator [ ] and the
index value i of the element.

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


// C Program to illustrate element access using array

// subscript

#include <stdio.h>

int main()

// array declaration and initialization

int arr[5] = { 15, 25, 35, 45, 55 };

// accessing element at index 2 i.e 3rd element

printf("Element at arr[2]: %d\n", arr[2]);

// accessing element at index 4 i.e last element

printf("Element at arr[4]: %d\n", arr[4]);

// accessing element at index 0 i.e first element

printf("Element at arr[0]: %d", arr[0]);

return 0;

1.7 Update Array Element


We can update the value of an element at the given index i in a similar way to accessing an
element by using the array subscript operator [ ] and assignment operator =.

array_name[i] = new_value;

1.8 Array Traversal


Traversal is the process in which we visit every element of the data structure. For C array
traversal, we use loops to iterate through each element of the array.
Array Traversal using for Loop

for (int i = 0; i < N; i++) {


array_name[i];
}
Example:

// C Program to demonstrate the use of array

#include <stdio.h>

int main()

// array declaration and initialization

int arr[5] = { 10, 20, 30, 40, 50 };

// modifying element at index 2

arr[2] = 100;

// traversing array using for loop

printf("Elements in Array: ");


for (int i = 0; i < 5; i++) {

printf("%d ", arr[i]);

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:
1. One Dimensional Arrays (1D Array)
2. Multidimensional Arrays

1. One Dimensional Array in C


The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only
one dimension.

Syntax of 1D Array in C
array_name [size];

// C Program to illustrate the use of 1D array

#include <stdio.h>

int main()

// 1d array declaration

int arr[5];
// 1d array initialization using for loop

for (int i = 0; i < 5; i++) {

arr[i] = i * i - 2 * i + 1;

printf("Elements of Array: ");

// printing 1d array by traversing using for loop

for (int i = 0; i < 5; i++) {

printf("%d ", arr[i]);

return 0;

Array of Characters (Strings)


In C, we store the words, i.e., a sequence of characters in the form of an array of characters
terminated by a NULL character. These are called strings in C language.

// C Program to illustrate strings

#include <stdio.h>

int main()

// creating array of character

char arr[6] = { 'G', 'e', 'e', 'k', 's', '\0' };

// printing string

int i = 0;

while (arr[i]) {

printf("%c", arr[i++]);

}
return 0;

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,
 size1: Size of the first dimension.
 size2: Size of the second dimension.

// C Program to illustrate 2d array


#include <stdio.h>

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;

B. Three-Dimensional Array in C
Another popular form of a multi-dimensional array is Three Dimensional Array or 3D Array.
A 3D array has exactly three dimensions. It can be visualized as a collection of 2D arrays
stacked on top of each other to create the third dimension.

Syntax of 3D Array in C
array_name [size1] [size2] [size3];
Example:

// C Program to illustrate the 3d array

#include <stdio.h>

int main()

// 3D array declaration

int arr[2][2][2] = { 10, 20, 30, 40, 50, 60 };

// printing elements

for (int i = 0; i < 2; i++) {

for (int j = 0; j < 2; j++) {

for (int k = 0; k < 2; k++) {

printf("%d ", arr[i][j][k]);


}

printf("\n");

printf("\n \n");

return 0;

Working with Pointers in C Programming


Pointers are a fundamental concept in C programming. They allow direct memory access and
manipulation, making them incredibly powerful but also requiring careful use.

A pointer is a variable that stores the memory address of another variable. Instead of
holding a direct value, it holds the address where the value is stored in memory. There are 2
important operators that we will use in pointers concepts i.e.
 Dereferencing operator(*) used to declare pointer variable and access the value stored
in the address.
 Address operator(&) used to returns the address of a variable or to access the address
of a variable to a pointer.

#include <stdio.h>

int main()

// taking an integer variable

int m = 100;

// pointer variable ptr that stores

// the address of variable m

int *ptr = &m;

// printing the value of variable m

printf("The Value of Variable m is: %d\n", m);

// printing the memory address of variable m

// in hexadecimal format
printf("The Memory Address of Variable m is: %p\n", &m);

// printing the value of ptr i.e.

// printing the memory address of variable m

// in hexadecimal format using pointer variable

printf("The Memory Address of Variable m is using ptr: %p\n", ptr);

return 0;

Important Points:
 %p format specifier is used to print the address stored in pointer variables.
 Printing a pointer with %d format specifier may result in a warning or undefined
behaviour because the size of a pointer (usually 4 or 8 bytes) may not match that of an
integer.
 The memory address format will always be in hexadecimal format(starting with 0x).
 C does not use the term “reference” explicitly (unlike C++), “referencing” in C usually
refers to obtaining the address of a variable using the address operator (&).
 Pointers are essential for dynamic memory allocation, providing control over memory
usage with functions like malloc, calloc, and free.

#include <stdio.h>

int main() {

// An integer variable

int a = 10;

// Create a pointer to integer (declaration)

int * ptr;

// Store the address of a inside pointer (initialization)

ptr = &a;

// Print the content of ptr

printf("ptr = %p\n", ptr);

// Get the value pointed by ptr (dereferencing)

printf("*ptr = %d", *ptr);

return 0;
}

The above demonstration can be understood by dividing it into three steps:


A. Pointer Declaration
To declare a pointer, we use the (*) dereference operator before its name. In pointer
declaration, we only declare the pointer but do not initialize it.
B. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the pointer variable.
We use the (&) addressof operator to get the memory address of a variable and then store
it in the pointer variable.
C. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the memory address
specified in the pointer. We use the same (*) dereferencing operator that we used in the
pointer declaration.

#include <stdio.h>

int main() {

// Storing string as pointer

char *s = "Geeks";

printf("%s", s);

return 0;

Types of Pointers in C
Pointers in C can be classified into many different types depending on the data it is pointing
to:
1. Integer Pointers
As the name suggests, these are the pointers that point to the integer values. These pointers
are pronounced as Pointer to Integer. Similarly, a pointer can point to any primitive data
type and is named accordingly.
Similarly, a pointer can point to any primitive data type. It can point also point to derived
data types such as arrays and user-defined data types such as structures.
2. Array Pointer
Pointers and Array are closely related to each other. Even the array name is the pointer to its
first element. They are also known as Pointer to Arrays.
3. Structure Pointer
The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure.
It can be declared in the same way as we declare the other primitive data types.
4. Function Pointers
Function pointers point to the functions. They are different from the rest of the pointers in
the sense that instead of pointing to the data, they point to the code.
5. Double Pointers
In C language, we can define a pointer that stores the memory address of another pointer.
Such pointers are called double-pointers or pointers-to-pointer. Instead of pointing to a data
value, they point to another pointer.
In C, we can create multi-level pointers with any number of levels such as – ***ptr3,
****ptr4, ******ptr5 and so on.
6. NULL Pointer
The Null Pointers are those pointers that do not point to any memory location. They can be
created by assigning a NULL value to the pointer. A pointer of any type can be assigned the
NULL value.
7. Void Pointer
The Void pointers in C are the pointers of type void. It means that they do not have any
associated data type. They are also called generic pointers as they can point to any type and
can be typecasted to any type.
8. Wild Pointers
The Wild Pointers are pointers that have not been initialized with something yet. These types
of C-pointers can cause problems in our programs and can eventually cause them to crash. If
values are updated using wild pointers, they could cause data abort or data corruption.
9. Constant Pointers
In constant pointers, the memory address stored inside the pointer is constant and cannot be
modified once it is defined. It will always point to the same memory address.
10. Pointer to Constant
The pointers pointing to a constant value that cannot be modified are called pointers to a
constant. Here we can only access the data pointed by the pointer, but cannot modify it.
Although, we can change the address stored in the pointer to constant.
Other Types of Pointers in C
There are also the following types of pointers available to use in C apart from those specified
above:
 Far pointer: A far pointer is typically 32-bit that can access memory outside the current
segment.
 Dangling pointer: A pointer pointing to a memory location that has been deleted (or
freed) is called a dangling pointer.
 Huge pointer: A huge pointer is 32-bit long containing segment address and offset
address.
 Complex pointer: Pointers with multiple levels of indirection.
 Near pointer: Near pointer is used to store 16-bit addresses means within the current
segment on a 16-bit machine.
 Normalized pointer: It is a 32-bit pointer, which has as much of its value in the segment
register as possible.
 File Pointer: The pointer to a FILE data type is called a stream pointer or a file pointer.

Size of Pointers in C
As pointers in C store the memory addresses, their size is independent of the type of data
they are pointing to. This size of pointers in C only depends on the system architecture.
The size of the pointers in C is equal for every pointer type. The size of the pointer does not
depend on the type it is pointing to. It only depends on the operating system and CPU
architecture. The size of pointers in C is
 8 bytes for a 64-bit System
 4 bytes for a 32-bit System

Advantages of Pointers
Following are the major advantages of pointers in C:
 Pointers are used for dynamic memory allocation and deallocation.
 An Array or a structure can be accessed efficiently with pointers
 Pointers are useful for accessing memory locations.
 Pointers are used to form complex data structures such as linked lists, graphs, trees, etc.
 Pointers reduce the length of the program and its execution time as well.
Disadvantages of Pointers
Pointers are vulnerable to errors and have following disadvantages:
 Memory corruption can occur if an incorrect value is provided to pointers.
 Pointers are a little bit complex to understand.
 Pointers are majorly responsible for memory leaks in C.
 Pointers are comparatively slower than variables in C.
 Uninitialized pointers might cause a segmentation fault.

1. Basics of Pointers and Operators

 What is a Pointer?
A pointer is a variable that stores the memory address of another variable.
Example:

int x = 10; // Variable `x` holds the value 10


int *ptr = &x; // Pointer `ptr` holds the address of `x`

 Pointer Operators:
o Address-of operator (&): Fetches the address of a variable. Example: int *p =
&x;
o Dereference operator (*): Accesses the value stored at the address a pointer
points to. Example: int y = *p; (retrieves the value of x through the pointer p).

2. Accessing the Address of a Variable

 Every variable in C is stored in memory, and each memory location has an address.
Using the address-of operator (&), you can access the address of a variable.

int x = 42;
printf("Address of x: %p\n", &x); // Prints the memory address of `x`

3. Declaring and Initializing Pointers

 Declaration: Use the asterisk (*) to declare a pointer.


Example:

int *ptr; // Declares a pointer to an integer

 Initialization: Assign a memory address to the pointer.


Example:
int x = 5;
int *ptr = &x; // Pointer `ptr` now holds the address of `x`

4. Accessing a Variable through Its Pointer


 A pointer can be used to indirectly access or modify the value of a variable by
dereferencing it.
Example:

int x = 10;

int *ptr = &x;

printf("Value of x: %d\n", *ptr); // Prints 10

*ptr = 20; // Modifies `x` through the pointer

printf("New value of x: %d\n", x); // Prints 20

5. Pointer Expressions

 You can perform arithmetic operations on pointers (only when they point to array
elements or contiguous memory locations).
Example:

int arr[] = {10, 20, 30};

int *ptr = arr; // Points to the first element of the array

printf("%d\n", *ptr); // 10

printf("%d\n", *(ptr + 1)); // 20 (pointer arithmetic)

6. Pointers and Functions

 Passing Pointers to Functions: Allows functions to directly modify the variable's


value in memory.

Example:

void updateValue(int *p) {

*p = 50; // Modifies the value of the variable pointed to by `p`

int main() {

int x = 10;

updateValue(&x);
printf("Updated x: %d\n", x); // Prints 50

return 0;

 Returning Pointers from Functions: A function can return a pointer to dynamically


allocated memory or an existing variable.

7. Array Using Pointers

 Pointers are closely related to arrays in C. The name of an array is a constant pointer to
its first element.

Example:

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

int *ptr = arr; // Pointer to the first element of the array

for (int i = 0; i < 5; i++) {

printf("%d ", *(ptr + i)); // Accessing array elements via pointer arithmetic

 Pointer vs. Array Notation:


Array elements can be accessed using pointers or subscript notation:

arr[2] == *(arr + 2); // Both give the same result

Key Notes on Pointers:

 Pointers must be initialized before use; uninitialized pointers can lead to undefined
behavior.
 Be cautious when using pointers to prevent issues like dangling pointers, memory
leaks, and segmentation faults.
 The NULL pointer is a special pointer used to indicate that it points to nothing.

-----------------------------------------------xxxx-------------------------------------------------

You might also like