POINTER
A pointer is defined as a derived data type that can store the address of
other C variables or a memory location.
We can access and manipulate the data stored in that memory location
using pointers.
Advantages
1. Pointers in C programming are helpful to access a memory location.
2. Pointers are an effective way to access the array structure elements.
3. Pointers are used for the allocation of dynamic memory and the distribution.
• Syntax of C Pointers
• The syntax of pointers is similar to the variable declaration in C, but we use the ( * )
dereferencing operator in the pointer declaration.
• datatype * ptr;
where
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
• How to Use Pointers?
• The use of pointers in C can be divided into three steps:
• Pointer Declaration Pointer Initialization
• Pointer Declaration
• In pointer declaration, we only declare the pointer but do not initialize it. To
declare a pointer, we use the ( * ) dereference operator before its name
• Example
• int *ptr;
• The pointer declared here will point to some random memory address as it is not initialized.
Such pointers are called wild pointers
• 2. Pointer Initialization
• Pointer initialization is the process where we assign some initial value to the pointer
variable. We generally use the ( & ) addressof operator to get the memory address of a
variable and then store it in the pointer variable.
• Example
• int var = 10;
int * ptr;
ptr = &var;
• We can also declare and initialize the pointer in a single step. This method is
called pointer definition as the pointer is declared and initialized at the same time.
• Example
• int *ptr = &var;
• void Avanthi()
• {
• int var = 50;
• // declare pointer variable
• int* ptr;
• // note that data type of ptr and var must be same
• ptr = &var;
• // assign the address of a variable to a pointer
• printf("Value at ptr = %p n", ptr);
• printf("Value at var = %d n", var);
• printf("Value at *ptr = %d n", *ptr);
• }
• // Driver program
• int main()
• {
• Avanthi();
• return 0;
• }
• Value at ptr = 0x7ffddb0db7e4
• Value at var = 50
• Value at *ptr = 50
C - POINTER TO POINTER
• A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
• Normally, a pointer contains the address of a variable.
• When we define a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the location that contains the actual value as shown
below.
• A variable that is a pointer to a pointer must be declared as such.
• This is done by placing an additional asterisk in front of its name. For example, the
following declaration declares a pointer to a pointer of type int −
• int **var;
• When a target value is indirectly pointed to by a pointer to a pointer, accessing that
value requires that the asterisk operator be applied twice, as is shown below in the
example −
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %dn", var );
printf("Value available at *ptr = %dn", *ptr );
printf("Value available at **pptr = %dn", **pptr);
return 0;
}
• When the above code is compiled and executed, it produces the following result −
• Value of var = 3000
• Value available at *ptr = 3000
• Value available at **pptr = 3000
• Pointers have many but easy concepts and they are very important to C programming. The following
important pointer concepts should be clear to any C programmer −
• Sr.No. Concept & Description
• 1 Pointer arithmetic
• There are four arithmetic operators that can be used in pointers: ++, --, +, -
• 2 Array of pointers
• You can define arrays to hold a number of pointers.
• 3 Pointer to pointer
• C allows you to have pointer on a pointer and so on.
• 4 Passing pointers to functions in C
• Passing an argument by reference or by address enable the passed argument to be changed in the calling
function by the called function.
• 5 Return pointer from functions in C
• C allows a function to return a pointer to the local variable, static variable, and dynamically allocated memory
as well.
• NULL Pointers
• It is always a good practice to assign a NULL value to a pointer variable in case you
do not have an exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a null pointer.
• The NULL pointer is a constant with a value of zero defined in several standard
libraries. Consider the following program −
• #include <stdio.h>
• int main () {
• int *ptr = NULL;
• printf("The value of ptr is : %xn", ptr );
• return 0;
• }
• Output: The value of ptr is 0
C - Pointer arithmetic
• A pointer in c is an address, which is a numeric value. Therefore, you can perform
arithmetic operations on a pointer just as you can on a numeric value. There are four
four arithmetic operators that can be used on pointers: ++, --, +, and -
• To understand pointer arithmetic, let us consider that ptr is an integer pointer which
points to the address 1000. Assuming 32-bit integers, let us perform the following
arithmetic operation on the pointer −
ptr++
After the above operation, the ptr will point to the location 1004 because each time
ptr is incremented, it will point to the next integer location which is 4 bytes next to the
current location. This operation will move the pointer to the next memory location
without impacting the actual value at the memory location.
• Incrementing a Pointer
• We prefer using a pointer in our program instead of an array because the variable
pointer can be incremented, unlike the array name which cannot be incremented
because it is a constant pointer. The following program increments the variable
pointer to access each succeeding element of the array −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++) {
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
/* move to the next location */
ptr++;
}
return 0;
}
• When the above code is compiled and executed, it produces the following result −
• Address of var[0] = bf882b30
• Value of var[0] = 10
• Address of var[1] = bf882b34
• Value of var[1] = 100
• Address of var[2] = bf882b38
• Value of var[2] = 200
• Decrementing a Pointer
• The same considerations apply to decrementing a pointer, which decreases its value by the
number of bytes of its data type as shown below −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--) {
printf("Address of var[%d] = %xn", i-1, ptr );
printf("Value of var[%d] = %dn", i-1, *ptr );
/* move to the previous location */
ptr--;
}
return 0;
}
• Address of var[2] = bfedbcd8
• Value of var[2] = 200
• Address of var[1] = bfedbcd4
• Value of var[1] = 100
• Address of var[0] = bfedbcd0
• Value of var[0] = 10
• Pointer Comparisons
• Pointers may be compared by using relational operators, such as ==, <, and >. If p1
and p2 point to variables that are related to each other, such as elements of the
same array, then p1 and p2 can be meaningfully compared.
• The following program modifies the previous example − one by incrementing the
variable pointer so long as the address to which it points is either less than or equal
to the address of the last element of the array, which is &var[MAX - 1] −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have address of the first element in pointer */
ptr = var;
i = 0;
while ( ptr <= &var[MAX - 1] ) {
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
/* point to the next location */
ptr++;
i++;
}
return 0;
}
• Address of var[0] = bfdbcb20
• Value of var[0] = 10
• Address of var[1] = bfdbcb24
• Value of var[1] = 100
• Address of var[2] = bfdbcb28
• Value of var[2] = 200
C POINTER ADDITION
• C pointer addition refers to adding a value to the pointer variable.
• The formula is as follows −
• new_address= current_address + (number * size_of(data type))
• 32-bit
• For 32-bit int variable, it will add 2 * number.
• 64-bit
• For 64-bit int variable, it will add 4 * number.
• Let's see the example of adding value to pointer variable on 64-bit architecture.
• #include<stdio.h>
• int main(){
• int number=50;
• int *p;//pointer to int
• p=&number;//stores the address of number variable
• printf("Address of p variable is %u n",p);
• p=p+3; //adding 3 to pointer variable
• printf("After adding 3: Address of p variable is %u n",p);
• return 0;
• }
• Address of p variable is 3214864300
• After adding 3: Address of p variable is 3214864312
• As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is
3214864312, i.e., 4*3=12 increment. Since we are using 64-bit architecture, it increments 12
• C Pointer Subtraction
• Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number
from a pointer will give an address. The formula of subtracting value from the pointer variable is
given below:
• new_address= current_address - (number * size_of(data type))
• 32-bit
• For 32-bit int variable, it will subtract 2 * number.
• 64-bit
• For 64-bit int variable, it will subtract 4 * number.
• Let's see the example of subtracting value from the pointer variable on 64-bit architecture.
• Distinguishing Features of Arrays and Pointers
• 1. Behavior of sizeof operator
• When used with arrays, sizeof operator returns the size in bytes occupied by the entire array
whereas when used with pointers, it returns the size in bytes of the pointer itself regardless of the
data types it points to.
• Example:
• #include <stdio.h>
•
• int main()
• {
• int arr[] = { 10, 20, 30, 40, 50, 60 };
• int* ptr = arr;
•
• // sizof(int) * (number of element in arr[]) is printed
• printf("Size of arr[] %ldn", sizeof(arr));
•
• // sizeof a pointer is printed which is same for all
• // type of pointers (char *, void *, etc)
• printf("Size of ptr %ld", sizeof(ptr));
• return 0;
• }
POINTER AND ARRAY RELATIONSHIP
• Pointers and arrays have a special relationship in C, just as they do in ANSI-C. An array
is represented by a variable that is associated with the address of its first storage
location.
• A pointer is also the address of a storage location with a defined type, so D permits
the use of the array [ ] index notation with both pointer variables and array variables.
For example, the following two D fragments are equivalent in meanin
• p = &a[0]; trace(a[2]);
• trace(p[2]);
The difference between pointers and arrays is that a pointer variable refers to a
separate piece of storage that contains the integer address of some other
storage. An array variable names the array storage itself, not the location of an
integer that in turn contains the location of the array. This difference is illustrated
in the following diagram:
• Properties of Array that Make it Resemble Pointers
• Although array and pointer are different concepts, the following properties of array make them
look similar.
• 1. Array name gives the address of the first element of the array
• When we use the array name in the program, it implicitly represents the memory address of the
first element in the array.
• Example:
•
• #include <stdio.h>
• int main()
• {
• int arr[] = { 10, 20, 30, 40, 50, 60 };
• // Assigns address of array to ptr
• int* ptr = arr;
• printf("Value of first element is %d", *ptr);
• return 0;
• }
• 2. Array members are accessed using pointer arithmetic
• The compiler uses pointer arithmetic to access the array elements. For example, an expression like
“arr[i]” is treated as *(arr + i) by the compiler. That is why the expressions like *(arr + i) work for
array arr, and expressions like ptr[i] also work for pointer ptr.
• Example:
•
• #include <stdio.h>
•
• int main()
• {
• int arr[] = {10, 20, 30, 40, 50, 60};
• int *ptr = arr;
• printf("arr[2] = %dn", arr[2]);
• printf("*(arr + 2) = %dn", *(arr + 2));
• printf("ptr[2] = %dn", ptr[2]);
• printf("*(ptr + 2) = %dn", *(ptr + 2));
• return 0;
• }
• 3. Array parameters are always passed as pointers, even when we use square brackets
• When an array is passed as a parameter to a function, the array name is converted to a pointer to its first element and the function
receives the pointer that points to the first element of the array instead of the entire array.
• #include <stdio.h>
• int fun(int ptr[])
• {
• int x = 10;
• // size of a pointer is printed
• printf("sizeof(ptr) = %dn", (int)sizeof(*ptr));
• // This allowed because ptr is a pointer, not array
• ptr = &x;
• printf("*ptr = %d ", *ptr);
• return 0;
• }
• int main()
• {
• int arr[] = { 10, 20, 30, 40, 50, 60 };
• // size of a array is printed
• printf("sizeof(arr) = %dn", (int)sizeof(arr));
• fun(arr);
• return 0;
• }
• 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.
• Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
• Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
• 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
• 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.
• 1. 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;
• #include<stdio.h>
• int main(){
• int i=0;
• int marks[5];//declaration of array
• marks[0]=80;//initialization of array
• marks[1]=60;
• marks[2]=70;
• marks[3]=85;
• marks[4]=75;
• //traversal of array
• for(i=0;i<5;i++)
• {
• printf("%d n",marks[i]);
• }//end of for loop
• return 0;
• }
• C Array: Declaration with Initialization
• We can initialize the c array at the time of declaration. Let's see the code.
• 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.
• int marks[]={20,30,40,50,60};
• Let's see the C program to declare and initialize the array in C.
• #include<stdio.h>
• int main(){
• int i=0;
• int marks[5]={20,30,40,50,60};//declaration and initialization of array
• //traversal of array
• for(i=0;i<5;i++){
• printf("%d n",marks[i]); return 0; }
• }
• C Array Example: Sorting an array
• In the following program, we are using bubble sort method to sort the array in ascending order.
• #include<stdio.h>
• void main ()
• {
• int i, j,temp;
• int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
• for(i = 0; i<10; i++)
• {
• for(j = i+1; j<10; j++)
• {
• if(a[j] > a[i])
• {
• temp = a[i];
• a[i] = a[j];
• a[j] = temp; } } }
• printf("Printing Sorted Element List ...n");
• for(i = 0; i<10; i++)
• {
• printf("%dn",a[i]);
• } }
• 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.
• data_type array_name[rows][columns];
• Consider the following example.
• 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.
• int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two-dimensional array example in C
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
• Storing elements in a matrix and printing it.
• #include <stdio.h>
• void main ()
• {
• int arr[3][3],i,j;
• for (i=0;i<3;i++)
• {
• for (j=0;j<3;j++)
• {
• printf("Enter a[%d][%d]: ",i,j);
• scanf("%d",&arr[i][j]);
• }
• }
• printf("n printing the elements ....n");
• for(i=0;i<3;i++)
• {
• printf("n");
• for (j=0;j<3;j++)
• {
• printf("%dt",arr[i][j]); } } }
• Array of Pointers in C
In C, a pointer array is a homogeneous collection of indexed pointer variables that are
references to a memory location.
It is generally used in C Programming when we want to point at multiple memory
locations of a similar data type in our C program.
We can access the data by dereferencing the pointer pointing to it
Syntax:
pointer_type *array_name [array_size];
Here,
pointer_type: Type of data the pointer is pointing to.
array_name: Name of the array of pointers.
array_size: Size of the array of pointers.
• // C program to demonstrate the use of array of pointers
• #include <stdio.h>
• int main()
• {
• // declaring some temp variables
• int var1 = 10;
• int var2 = 20;
• int var3 = 30;
• // array of pointers to integers
• int* ptr_arr[3] = { &var1, &var2, &var3 };
• // traversing using loop
• for (int i = 0; i < 3; i++) {
• printf("Value of var%d: %dtAddress: %pn", i + 1, *ptr_arr[i], ptr_arr[i]);
• }
• return 0;
• }
As shown in the above example, each element of the
array is a pointer pointing to an integer. We can access
the value of these integers by first selecting the array
element and then dereferencing it to get the value.
• Array of Pointers to Character
• One of the main applications of the array of pointers is to store multiple strings as
an array of pointers to characters. Here, each pointer in the array is a character
pointer that points to the first character of the string.
• Syntax:
• char *array_name [array_size];
• After that, we can assign a string of any length to these pointers.
• Example:
• char* arr[5]
• = { “rkr", “rkred", “rkredd", “rkreedd", “rkreddyijjam" }
• This method of storing strings has the advantage of the traditional array of strings. Consider
the following two examples:
• Example 1:
• // C Program to print Array of strings without array of pointers
• #include <stdio.h>
• int main()
• {
• char str[3][10] = { “Rkr", “RKres", “Rkreddy" };
• printf("String array Elements are:n");
• for (int i = 0; i < 3; i++) {
• printf("%sn", str[i]);
• }
• return 0;
• }
• In the above program, we have declared the 3 rows and 10 columns of our array of strings.
• But because of predefining the size of the array of strings the space consumption of the program increases if
the memory is not utilized properly or left unused.
• Now let’s try to store the same strings in an array of pointers.
• // C program to illustrate the use of array of pointers to
• // characters
• #include <stdio.h>
• int main()
• {
• char* arr[3] = { rkr", “rkredd", “rkreddybijjam" };
• for (int i = 0; i < 3; i++) {
• printf("%sn", arr[i]);
• }
• return 0;
• }
• Array of Pointers to Different Types
• Not only we can define the array of pointers for basic data types like int, char, float, etc. but we
can also define them for derived and user-defined data types such as arrays, structures, etc. Let’s
consider the below example where we create an array of pointers pointing to a function for
performing the different operations.
• Application of Array of Pointers
• An array of pointers is useful in a wide range of cases. Some of these applications are listed
below:
• It is most commonly used to store multiple strings.
• It is also used to implement LinkedHashMap in C and also in the Chaining technique of collision
resolving in Hashing.
• It is used in sorting algorithms like bucket sort.
• It can be used with any pointer type so it is useful when we have separate declarations of multiple
entities and we want to store them in a single place.
• Disadvantages of Array of Pointers
• The array of pointers also has its fair share of disadvantages and should be used when the
advantages outweigh the disadvantages. Some of the disadvantages of the array of pointers are:
• Higher Memory Consumption: An array of pointers requires more memory as compared to plain
arrays because of the additional space required to store pointers.
• Complexity: An array of pointers might be complex to use as compared to a simple array.
• Prone to Bugs: As we use pointers, all the bugs associated with pointers come with it so we need
to handle them carefully.
• // C program to illustrate the use of array of pointers to // function
• #include <stdio.h>
• // some basic arithmetic operations
• void add(int a, int b) {
• printf("Sum : %dn", a + b);
• }
• void subtract(int a, int b) {
• printf("Difference : %dn", a - b);
• }
• void multiply(int a, int b) {
• printf("Product : %dn", a * b);
• }
• void divide(int a, int b) {
• printf("Quotient : %d", a / b);
• }
• int main() {
• int x = 50, y = 5;
• // array of pointers to function of return type int
• void (*arr[4])(int, int)
• = { &add, &subtract, &multiply, ÷ };
• for (int i = 0; i < 4; i++) {
• arr[i](x, y);
• }
• return 0;
• }

Pointers and single &multi dimentionalarrays.pptx

  • 1.
    POINTER A pointer isdefined as a derived data type that can store the address of other C variables or a memory location. We can access and manipulate the data stored in that memory location using pointers. Advantages 1. Pointers in C programming are helpful to access a memory location. 2. Pointers are an effective way to access the array structure elements. 3. Pointers are used for the allocation of dynamic memory and the distribution.
  • 2.
    • Syntax ofC Pointers • The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the pointer declaration. • datatype * ptr; where • ptr is the name of the pointer. • datatype is the type of data it is pointing to.
  • 3.
    • How toUse Pointers? • The use of pointers in C can be divided into three steps: • Pointer Declaration Pointer Initialization • Pointer Declaration • In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the ( * ) dereference operator before its name • Example • int *ptr; • The pointer declared here will point to some random memory address as it is not initialized. Such pointers are called wild pointers
  • 4.
    • 2. PointerInitialization • Pointer initialization is the process where we assign some initial value to the pointer variable. We generally use the ( & ) addressof operator to get the memory address of a variable and then store it in the pointer variable. • Example • int var = 10; int * ptr; ptr = &var; • We can also declare and initialize the pointer in a single step. This method is called pointer definition as the pointer is declared and initialized at the same time. • Example • int *ptr = &var;
  • 5.
    • void Avanthi() •{ • int var = 50; • // declare pointer variable • int* ptr; • // note that data type of ptr and var must be same • ptr = &var; • // assign the address of a variable to a pointer • printf("Value at ptr = %p n", ptr); • printf("Value at var = %d n", var); • printf("Value at *ptr = %d n", *ptr); • } • // Driver program • int main() • { • Avanthi(); • return 0; • }
  • 6.
    • Value atptr = 0x7ffddb0db7e4 • Value at var = 50 • Value at *ptr = 50
  • 7.
    C - POINTERTO POINTER • A pointer to a pointer is a form of multiple indirection, or a chain of pointers. • Normally, a pointer contains the address of a variable. • When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below. • A variable that is a pointer to a pointer must be declared as such. • This is done by placing an additional asterisk in front of its name. For example, the following declaration declares a pointer to a pointer of type int −
  • 8.
    • int **var; •When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example −
  • 9.
    #include <stdio.h> int main() { int var; int *ptr; int **pptr; var = 3000; /* take the address of var */ ptr = &var; /* take the address of ptr using address of operator & */ pptr = &ptr; /* take the value using pptr */ printf("Value of var = %dn", var ); printf("Value available at *ptr = %dn", *ptr ); printf("Value available at **pptr = %dn", **pptr); return 0; }
  • 10.
    • When theabove code is compiled and executed, it produces the following result − • Value of var = 3000 • Value available at *ptr = 3000 • Value available at **pptr = 3000
  • 11.
    • Pointers havemany but easy concepts and they are very important to C programming. The following important pointer concepts should be clear to any C programmer − • Sr.No. Concept & Description • 1 Pointer arithmetic • There are four arithmetic operators that can be used in pointers: ++, --, +, - • 2 Array of pointers • You can define arrays to hold a number of pointers. • 3 Pointer to pointer • C allows you to have pointer on a pointer and so on. • 4 Passing pointers to functions in C • Passing an argument by reference or by address enable the passed argument to be changed in the calling function by the called function. • 5 Return pointer from functions in C • C allows a function to return a pointer to the local variable, static variable, and dynamically allocated memory as well.
  • 12.
    • NULL Pointers •It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer. • The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program − • #include <stdio.h> • int main () { • int *ptr = NULL; • printf("The value of ptr is : %xn", ptr ); • return 0; • } • Output: The value of ptr is 0
  • 13.
    C - Pointerarithmetic • A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. There are four four arithmetic operators that can be used on pointers: ++, --, +, and - • To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer − ptr++ After the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location. This operation will move the pointer to the next memory location without impacting the actual value at the memory location.
  • 14.
    • Incrementing aPointer • We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array −
  • 15.
    #include <stdio.h> const intMAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = var; for ( i = 0; i < MAX; i++) { printf("Address of var[%d] = %xn", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); /* move to the next location */ ptr++; } return 0; }
  • 16.
    • When theabove code is compiled and executed, it produces the following result − • Address of var[0] = bf882b30 • Value of var[0] = 10 • Address of var[1] = bf882b34 • Value of var[1] = 100 • Address of var[2] = bf882b38 • Value of var[2] = 200
  • 17.
    • Decrementing aPointer • The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below − #include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = &var[MAX-1]; for ( i = MAX; i > 0; i--) { printf("Address of var[%d] = %xn", i-1, ptr ); printf("Value of var[%d] = %dn", i-1, *ptr ); /* move to the previous location */ ptr--; } return 0; }
  • 18.
    • Address ofvar[2] = bfedbcd8 • Value of var[2] = 200 • Address of var[1] = bfedbcd4 • Value of var[1] = 100 • Address of var[0] = bfedbcd0 • Value of var[0] = 10
  • 19.
    • Pointer Comparisons •Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared. • The following program modifies the previous example − one by incrementing the variable pointer so long as the address to which it points is either less than or equal to the address of the last element of the array, which is &var[MAX - 1] −
  • 20.
    #include <stdio.h> const intMAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have address of the first element in pointer */ ptr = var; i = 0; while ( ptr <= &var[MAX - 1] ) { printf("Address of var[%d] = %xn", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); /* point to the next location */ ptr++; i++; } return 0; }
  • 21.
    • Address ofvar[0] = bfdbcb20 • Value of var[0] = 10 • Address of var[1] = bfdbcb24 • Value of var[1] = 100 • Address of var[2] = bfdbcb28 • Value of var[2] = 200
  • 22.
    C POINTER ADDITION •C pointer addition refers to adding a value to the pointer variable. • The formula is as follows − • new_address= current_address + (number * size_of(data type)) • 32-bit • For 32-bit int variable, it will add 2 * number. • 64-bit • For 64-bit int variable, it will add 4 * number. • Let's see the example of adding value to pointer variable on 64-bit architecture.
  • 23.
    • #include<stdio.h> • intmain(){ • int number=50; • int *p;//pointer to int • p=&number;//stores the address of number variable • printf("Address of p variable is %u n",p); • p=p+3; //adding 3 to pointer variable • printf("After adding 3: Address of p variable is %u n",p); • return 0; • } • Address of p variable is 3214864300 • After adding 3: Address of p variable is 3214864312 • As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is 3214864312, i.e., 4*3=12 increment. Since we are using 64-bit architecture, it increments 12
  • 24.
    • C PointerSubtraction • Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a pointer will give an address. The formula of subtracting value from the pointer variable is given below: • new_address= current_address - (number * size_of(data type)) • 32-bit • For 32-bit int variable, it will subtract 2 * number. • 64-bit • For 64-bit int variable, it will subtract 4 * number. • Let's see the example of subtracting value from the pointer variable on 64-bit architecture. • Distinguishing Features of Arrays and Pointers • 1. Behavior of sizeof operator • When used with arrays, sizeof operator returns the size in bytes occupied by the entire array whereas when used with pointers, it returns the size in bytes of the pointer itself regardless of the data types it points to.
  • 25.
    • Example: • #include<stdio.h> • • int main() • { • int arr[] = { 10, 20, 30, 40, 50, 60 }; • int* ptr = arr; • • // sizof(int) * (number of element in arr[]) is printed • printf("Size of arr[] %ldn", sizeof(arr)); • • // sizeof a pointer is printed which is same for all • // type of pointers (char *, void *, etc) • printf("Size of ptr %ld", sizeof(ptr)); • return 0; • }
  • 26.
    POINTER AND ARRAYRELATIONSHIP • Pointers and arrays have a special relationship in C, just as they do in ANSI-C. An array is represented by a variable that is associated with the address of its first storage location. • A pointer is also the address of a storage location with a defined type, so D permits the use of the array [ ] index notation with both pointer variables and array variables. For example, the following two D fragments are equivalent in meanin • p = &a[0]; trace(a[2]); • trace(p[2]);
  • 27.
    The difference betweenpointers and arrays is that a pointer variable refers to a separate piece of storage that contains the integer address of some other storage. An array variable names the array storage itself, not the location of an integer that in turn contains the location of the array. This difference is illustrated in the following diagram:
  • 28.
    • Properties ofArray that Make it Resemble Pointers • Although array and pointer are different concepts, the following properties of array make them look similar. • 1. Array name gives the address of the first element of the array • When we use the array name in the program, it implicitly represents the memory address of the first element in the array. • Example: • • #include <stdio.h> • int main() • { • int arr[] = { 10, 20, 30, 40, 50, 60 }; • // Assigns address of array to ptr • int* ptr = arr; • printf("Value of first element is %d", *ptr); • return 0; • }
  • 29.
    • 2. Arraymembers are accessed using pointer arithmetic • The compiler uses pointer arithmetic to access the array elements. For example, an expression like “arr[i]” is treated as *(arr + i) by the compiler. That is why the expressions like *(arr + i) work for array arr, and expressions like ptr[i] also work for pointer ptr. • Example: • • #include <stdio.h> • • int main() • { • int arr[] = {10, 20, 30, 40, 50, 60}; • int *ptr = arr; • printf("arr[2] = %dn", arr[2]); • printf("*(arr + 2) = %dn", *(arr + 2)); • printf("ptr[2] = %dn", ptr[2]); • printf("*(ptr + 2) = %dn", *(ptr + 2)); • return 0; • }
  • 30.
    • 3. Arrayparameters are always passed as pointers, even when we use square brackets • When an array is passed as a parameter to a function, the array name is converted to a pointer to its first element and the function receives the pointer that points to the first element of the array instead of the entire array. • #include <stdio.h> • int fun(int ptr[]) • { • int x = 10; • // size of a pointer is printed • printf("sizeof(ptr) = %dn", (int)sizeof(*ptr)); • // This allowed because ptr is a pointer, not array • ptr = &x; • printf("*ptr = %d ", *ptr); • return 0; • } • int main() • { • int arr[] = { 10, 20, 30, 40, 50, 60 }; • // size of a array is printed • printf("sizeof(arr) = %dn", (int)sizeof(arr)); • fun(arr); • return 0; • }
  • 31.
    • Array • Anarray 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.
  • 32.
    • Properties ofArray • The array contains the following properties. • Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes. • Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location. • 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.
  • 33.
    • Advantage ofC 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 • 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.
  • 34.
    • Declaration ofC 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. • 1. 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;
  • 35.
    • #include<stdio.h> • intmain(){ • int i=0; • int marks[5];//declaration of array • marks[0]=80;//initialization of array • marks[1]=60; • marks[2]=70; • marks[3]=85; • marks[4]=75; • //traversal of array • for(i=0;i<5;i++) • { • printf("%d n",marks[i]); • }//end of for loop • return 0; • }
  • 36.
    • C Array:Declaration with Initialization • We can initialize the c array at the time of declaration. Let's see the code. • 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. • int marks[]={20,30,40,50,60}; • Let's see the C program to declare and initialize the array in C. • #include<stdio.h> • int main(){ • int i=0; • int marks[5]={20,30,40,50,60};//declaration and initialization of array • //traversal of array • for(i=0;i<5;i++){ • printf("%d n",marks[i]); return 0; } • }
  • 37.
    • C ArrayExample: Sorting an array • In the following program, we are using bubble sort method to sort the array in ascending order. • #include<stdio.h> • void main () • { • int i, j,temp; • int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23}; • for(i = 0; i<10; i++) • { • for(j = i+1; j<10; j++) • { • if(a[j] > a[i]) • { • temp = a[i]; • a[i] = a[j]; • a[j] = temp; } } } • printf("Printing Sorted Element List ...n"); • for(i = 0; i<10; i++) • { • printf("%dn",a[i]); • } }
  • 38.
    • Two DimensionalArray 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. • data_type array_name[rows][columns]; • Consider the following example. • int twodimen[4][3]; • Here, 4 is the number of rows, and 3 is the number of columns.
  • 39.
    • Initialization of2D 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. • int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
  • 40.
    Two-dimensional array examplein C #include<stdio.h> int main(){ int i=0,j=0; int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; //traversing 2D array for(i=0;i<4;i++){ for(j=0;j<3;j++){ printf("arr[%d] [%d] = %d n",i,j,arr[i][j]); }//end of j }//end of i return 0; }
  • 41.
    • Storing elementsin a matrix and printing it. • #include <stdio.h> • void main () • { • int arr[3][3],i,j; • for (i=0;i<3;i++) • { • for (j=0;j<3;j++) • { • printf("Enter a[%d][%d]: ",i,j); • scanf("%d",&arr[i][j]); • } • } • printf("n printing the elements ....n"); • for(i=0;i<3;i++) • { • printf("n"); • for (j=0;j<3;j++) • { • printf("%dt",arr[i][j]); } } }
  • 42.
    • Array ofPointers in C In C, a pointer array is a homogeneous collection of indexed pointer variables that are references to a memory location. It is generally used in C Programming when we want to point at multiple memory locations of a similar data type in our C program. We can access the data by dereferencing the pointer pointing to it Syntax: pointer_type *array_name [array_size]; Here, pointer_type: Type of data the pointer is pointing to. array_name: Name of the array of pointers. array_size: Size of the array of pointers.
  • 43.
    • // Cprogram to demonstrate the use of array of pointers • #include <stdio.h> • int main() • { • // declaring some temp variables • int var1 = 10; • int var2 = 20; • int var3 = 30; • // array of pointers to integers • int* ptr_arr[3] = { &var1, &var2, &var3 }; • // traversing using loop • for (int i = 0; i < 3; i++) { • printf("Value of var%d: %dtAddress: %pn", i + 1, *ptr_arr[i], ptr_arr[i]); • } • return 0; • }
  • 44.
    As shown inthe above example, each element of the array is a pointer pointing to an integer. We can access the value of these integers by first selecting the array element and then dereferencing it to get the value.
  • 45.
    • Array ofPointers to Character • One of the main applications of the array of pointers is to store multiple strings as an array of pointers to characters. Here, each pointer in the array is a character pointer that points to the first character of the string. • Syntax: • char *array_name [array_size]; • After that, we can assign a string of any length to these pointers. • Example: • char* arr[5] • = { “rkr", “rkred", “rkredd", “rkreedd", “rkreddyijjam" }
  • 47.
    • This methodof storing strings has the advantage of the traditional array of strings. Consider the following two examples: • Example 1: • // C Program to print Array of strings without array of pointers • #include <stdio.h> • int main() • { • char str[3][10] = { “Rkr", “RKres", “Rkreddy" }; • printf("String array Elements are:n"); • for (int i = 0; i < 3; i++) { • printf("%sn", str[i]); • } • return 0; • }
  • 48.
    • In theabove program, we have declared the 3 rows and 10 columns of our array of strings. • But because of predefining the size of the array of strings the space consumption of the program increases if the memory is not utilized properly or left unused. • Now let’s try to store the same strings in an array of pointers. • // C program to illustrate the use of array of pointers to • // characters • #include <stdio.h> • int main() • { • char* arr[3] = { rkr", “rkredd", “rkreddybijjam" }; • for (int i = 0; i < 3; i++) { • printf("%sn", arr[i]); • } • return 0; • }
  • 49.
    • Array ofPointers to Different Types • Not only we can define the array of pointers for basic data types like int, char, float, etc. but we can also define them for derived and user-defined data types such as arrays, structures, etc. Let’s consider the below example where we create an array of pointers pointing to a function for performing the different operations. • Application of Array of Pointers • An array of pointers is useful in a wide range of cases. Some of these applications are listed below: • It is most commonly used to store multiple strings. • It is also used to implement LinkedHashMap in C and also in the Chaining technique of collision resolving in Hashing. • It is used in sorting algorithms like bucket sort. • It can be used with any pointer type so it is useful when we have separate declarations of multiple entities and we want to store them in a single place. • Disadvantages of Array of Pointers • The array of pointers also has its fair share of disadvantages and should be used when the advantages outweigh the disadvantages. Some of the disadvantages of the array of pointers are: • Higher Memory Consumption: An array of pointers requires more memory as compared to plain arrays because of the additional space required to store pointers. • Complexity: An array of pointers might be complex to use as compared to a simple array. • Prone to Bugs: As we use pointers, all the bugs associated with pointers come with it so we need to handle them carefully.
  • 50.
    • // Cprogram to illustrate the use of array of pointers to // function • #include <stdio.h> • // some basic arithmetic operations • void add(int a, int b) { • printf("Sum : %dn", a + b); • } • void subtract(int a, int b) { • printf("Difference : %dn", a - b); • } • void multiply(int a, int b) { • printf("Product : %dn", a * b); • } • void divide(int a, int b) { • printf("Quotient : %d", a / b); • } • int main() { • int x = 50, y = 5; • // array of pointers to function of return type int • void (*arr[4])(int, int) • = { &add, &subtract, &multiply, ÷ }; • for (int i = 0; i < 4; i++) { • arr[i](x, y); • } • return 0; • }