UNIT-IV C LANGUAGE FYBSC IT

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Pointer:

 The pointer in C language is a variable which stores the address of another variable.
 Since Pointer is also a kind of variable , thus pointer itself will be stored at some
different memory location.
 This variable can be of typeint, char, float etc.

Address in C:
 Whenever a variable is defined in C language, a memory location is assigned for it, in
which it's value will be stored.
 We can easily check this memory address, using the & operator.
 If var is the name of the variable, then &var will give it's address.

Example:
#include<stdio.h>
int main()
{
int var = 7;
printf("Value of the variable var is: %d\n", var);
printf("Memory address of the variable var in Decimal is: %d\n", &var);
// d for decimal value
printf("Memory address of the variable var in Hexadecimal is: %x\n", &var);
// x for hexadecimal
return 0;
}

Declaring a pointer:
The pointer in c language is declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.

Syntax:
Data_type *var_name;

E.g.:
int *a;
Here, a is a pointer variable which will holds the address of another variable.

Program:
#include<stdio.h>
int main()
{
int number=50;
int *p; //pointer declaration
p=&number; // pointer initialization stores the address of number variable
printf("Address of p variable is %x \n",p);
return 0;
}

Accessing variables through pointers:


 ‘&’ is the reference operator
 ‘*’ is the dereference operator

Accessing variables through pointers:


We can access the value of the variable by using asterisk (*) - it is known as dereference
operator.

Program:
#include <stdio.h>
int main()
{
//normal variable
int num = 100;
//pointer variable
int *ptr;
//pointer initialization
ptr = &num;
//printing the value
printf("value of num = %d\n", *ptr);
return 0;
}

Output:
value of num = 100

Pointer to Pointer:
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.
The following declaration declares a pointer to a pointer of type int :
int **var, ***var;

program 1:
#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 = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}

Output:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

program 2:
#include <stdio.h>
int main ()
{
int var,*ptr1,**ptr2,***ptr3;
var = 3000;
ptr1 = &var;
ptr2 = &ptr1;
ptr3 = &ptr2;
printf("Value of var = %d\n", var );
printf("Value available at *ptr1 = %d\n", *ptr1 );
printf("Value available at **ptr2 = %d\n",**ptr2);
printf("Value available at ***ptr3 = %d\n", ***ptr3);
return 0;
}

Output:
Value of var = 3000
Value available at *ptr1 = 3000
Value available at **ptr2 = 3000
Value available at ***ptr3 = 3000

Call by value and Call by reference in C:


There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.

Call by value in C
 In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.
 In call by value method, we cannot modify the value of the actual parameter by the
formal parameter.
 In call by value, different memory is allocated for actual and formal parameters since
the value of the actual parameter is copied into the formal parameter.
 The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.

PROGRAM FOR CALL BY VALUE


#include<stdio.h>
void change(int num) //formal parameter
{
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main()
{
int x=100;
printf("Before function call x=%d \n", x);
change(x); //passing value in function actual parameter
printf("After function call x=%d \n", x);
return 0;
}

OUTPUT:
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C
 In call by reference, the address of the variable is passed into the function call as the
actual parameter.
 The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.

PROGRAM:
#include<stdio.h>
void change(int *num)
{
printf("Before adding value inside function num=%d \n",*num);
*num=*num+10;
printf("After adding value inside function num=%d \n", *num);
}
int main()
{
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}

OUTPUT:
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=110
After function call x=110
Structure and pointer:
Arrow (->) is used to access structure member using pointer.

Program:
#include <stdlib.h>
#include<stdio.h>
struct student
{
int roll;
char name[20];
}s1={10,"neha"};
void data(struct student*);
int main()
{
data(&s1);
return 0;
}
void data(struct student *p)
{
printf("roll no is %d\n",p->roll);
printf("roll no is %d\n",(*p).roll);
printf("name is %s\n",p->name);
printf("roll no is %s\n",(*p).name);
}

Output:
roll no is 10
roll no is 10
name is neha
roll no is neha

NULL Pointer:
 A NULL pointer is defined as a special pointer value that points to nowhere in the
memory.
 Null is a built-in constant that has a value of zero and NULL is defined under stdio.h
header file.
E.g.:
#include<stdio.h>
int *p=NULL;

Here, p is a NULL pointer, this indicates that the pointer variable p does not point to
any part of the memory.

Compatibility:
 We should not store the address of a data variable of one type into a pointer variable
of another type.
 During assigning we should see that the type of variable and type of pointer variable
should be of same type otherwise it results in syntax error.

E.g. 1:
int a=10;
int *p;
p=&a;
// valid: here pointer variable ‘p’ is of integer type and variable a is also of type integer
so type of both variables are compatible.

Eg 2:
int a=10;
float *p;
p=&a;
// invalid: here pointer variable ‘p’ is of float type and variable a is of integer so type of
both variables are in-compatible.

Pointer Arithmetic in C
 We can perform arithmetic operations on the pointers like addition,
subtraction, etc.
 However, as we know that pointer contains the address, the result of an
arithmetic operation performed on the pointer will also be a pointer if the
other operand is of type integer.
 In pointer-from-pointer subtraction, the result will be an integer value.
Following arithmetic operations are possible on the pointer in C language:
1. Increment
2. Decrement
3. Addition
4. Subtraction

1. Incrementing Pointer in C
 If we increment a pointer by 1, the pointer will start pointing to the immediate
next location.
 This is somewhat different from the general arithmetic since the value of the
pointer will get increased by the size of the data type to which the pointer is
pointing.
 We can traverse an array by using the increment operation on a pointer which
will keep pointing to every element of the array, perform some operation on
that, and update itself in a loop.

Example:
#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+1;
printf("After increment: Address of p variable is %u \n",p);
// in our case, p will get incremented by 4 bytes.
return 0;
}

Output:
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304

Traversing an array by using pointer


#include<stdio.h>
void main ()
{
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
int i;
printf("printing array elements...\n");
for(i = 0; i< 5; i++)
{
printf("%d ",*(p+i));
}
}

Output
Printing array elements...
1 2 3 4 5

2. Decrementing Pointer in C
 Like increment, we can decrement a pointer variable. If we decrement a
pointer, it will start pointing to the previous location.

Example:
include <stdio.h>
void 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-1;
printf("After decrement: Address of p variable is %u \n",p); // P will now point to t
he immidiate previous location.
}

Output
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
ARRAY:
 An array is defined as a collection of elements of similar data type.
 All the elements of an array are stored in consecutive memory locations i.e. one after the
other or in a sequence in main memory.
 All the elements shares common array name and they are accessed using index numbers.

Eg: Consider an array of Marks of 5 student as shown below:

80 90 45 99 100

Marks [0] Marks [1] Marks [2] Marks [3] Marks [4]

Here, Marks is name of the array and [0], [1], [2], [3], [4] are the index numbers.

Properties of Array:
1. Array elements are stored in contiguous memory.
2. Array name represents its base address. The base address is the address of the first
element of the array.
3. Array’s index starts with 0 and ends with N-1. Here, N stands for the number of elements.
For Example, there is an integer array of 5 elements, then it’s indexing will be 0 to 4.
4. Array elements are accessed by using an integer index.

Types of Array:
1. Single Dimensional Array( 1-D)
2. Multi-Dimensional Array (2-D)

1. Single Dimensional Array( 1-D):


 Arrays with one set of square bracket ‘[]’ are called single dimensional array .
 A single-dimensional array or 1-D array is a linear list consisting of related and similar
data items.

Declaration of Single Dimensional Array:


Syntax: Data_type array_Name [array size] ;
Example: int a[6];
Here, the compiler will reserve 6 locations (4*6=24 bytes) for the array a. In each of the
location we can store an integer value. The memory allocated by the compiler is pictorially
represented as:

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

Initialization of Single-dimensional Array:


Assigning the required data to a variable before processing is called initialization.

Different ways of initializing arrays:

1. Initialization all specified memory location:


Array can be initialized at the time of declaration when their initial values are known in
advance.
Example:
int m[5]={12,32,43,54,65};

During Compilation, 5 contiguous memory locations are reserved by the compiler for
the array ‘m’ and all the locations are initialized as shown below:

12 32 43 54 65

m[0] m[1] m[2] m[3] m[4]


2. Partial array initialization:
If the number of values to be initialized is less than the size of the array, then the
elements are initialized in the order from 0th location. The remaining location will be
initialized to zero automatically.
Example: int m[5]={14,23};

Here Compiler will allocate 5 memory locations and initializes first two locations with 14 and
23.The next set of memory locations will automatically initialize to zero by the compiler.

14 23 0 0 0

m[0] m[1] m[2] m[3] m[4]

3. Initialization without size:


While creating an array size is not mandatory but if you are creating an array without
specifying the array size then initialization is mandatory.

Example: int p[ ]={32,54,53,78};

Here,We have not mentioned the array size, so array size will be the toal number of elements
specified.so the array size will be set to 4 automatically.

32 54 53 78

P[0] p[1] p[2] p[3]

4. Array initializing of a string:


In array string ends with a NULL character (‘\0’) and this NULL character also takes one
byte in the memory, so in case of array of string size will be total character + 1 (for
NULL).
Example:
char c[7]={‘s’,’a’,’h’,’y’,’o’,’g’,’\0’};
OR
char c[ ]= ”Sahyog”;
Reading & Writing Single Dimensional Array in C Language:

Reading single dimensional array:


 Using index no. we can access the element of the array.
 Eg. int a[]={10,11,12,13,14};
 Here, index no of 10 is 0,index of 11 is 1,index of 12 is 2 ,index of 13 is 3,index of 14
is 4

Program to display elements of array without using loop:

Program to display elements of an array using any loop.


WAP to take input from the user in an array without using loop.

WAP in C to display elements of an array using any loop.


2. Multi-Dimensional Array (2-D):
An array with 2 set of square brackets ‘[] []’ are called 2-dimensional array. Array with 2 or
more dimensions are called multi-dimensional array.

Declaration of Multi-Dimensional Array:


Syntax: Data_type array_name[size1][size2];
Example: int a[2][3];

Here, array ‘a’ is 2-dimensional array with 2 rows and 3 columns. This declaration informs
the compiler to reserve 6 locations (2*3=6) contiguously one after the other. Total memory
reserved is 6*4 (int takes 4 byte)=24 bytes.

Initialization of 2-D Array:


Assigning required value to a variable before processing is called initialization.

Syntax:
data_type variable_name[size1][size2]={{val1,val2},{val3,val4}};

Example:
int first[3][4]={ {11,32,53,74},
{55,47,26,32},
{43,54,23,11}
};
The declaration indicates that array ‘first’ has 3 rows and 4 columns. The pictorial
representation of this 2-D array is:
Reading & Writing Multi Dimensional Array:

1. WAP to display element of 2-D array without using loop.

#include<stdio.h>
int main()
{
int a[2][2]={ {21,42},{53,74} };
printf("first element is: %d\n",a[0][0]);
printf("second element is: %d\n",a[0][1]);
printf("third element is: %d\n",a[1][0]);
printf("fourth element is: %d\n",a[1][1]);
return 0;
}

Output:
first element is: 21
second element is: 42
third element is: 53
fourth element is: 74

2. WAP to take input from user using loop:

#include<stdio.h>
using namespace std;
int main()
{
int a[2][2];
printf("Enter Elements one by one:\n");
for(int i=0;i<=1;i++)
{
for(int j=0;j<=1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Entered Elements are:\n");
for(int i=0;i<=1;i++)
{
for(int j=0;j<=1;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
return 0;
}

Output:
Enter Elements one by one:
4
3
2
1
Entered Elements are:
4 3
2 1

Array of Strings
In C programming String is a 1-D array of characters and is defined as an array of
characters. But an array of strings in C is a two-dimensional array of character types. Each
String is terminated with a null character (\0). It is an application of a 2d array.

Syntax:
char variable_name[r] = {list of string};

Here,
 var_name is the name of the variable in C.
 r is the maximum number of string values that can be stored in a string array.
 c is the maximum number of character values that can be stored in each
string array.
Example:
#include <stdio.h>
int main()
{
char arr[3][10] = {"Geek", "Geeks", "Geekfor"};
printf("String array Elements are:\n");
for (int i = 0; i < 3; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}

Output
String array Elements are:
Geek
Geeks
Geekfor

Pointer to Array:
 We can use a pointer to point to an array, and then we can use that pointer to
access the array elements.
 To access array element using pointer first we need to assign base address in
pointer variable.
 Then to we need to increment the pointer to access all the elements of array.

Example:
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}

OR
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p+i);

}
return 0;
}

Output:
12345

Creating a pointer for the string


 The variable name of the string str holds the address of the first element of
the array i.e., it points at the starting memory address.
 So, we can create a character pointer ptr and store the address of the
string str variable in it. This way, ptr will point at the string str.
 In the following code we are assigning the address of the string str to the
pointer ptr.
char *ptr = str;

We can represent the character pointer variable ptr as follows.

The pointer variable ptr is allocated memory address 8000 and it holds the
address of the string variable str i.e., 1000.

Accessing string via pointer


 To access and print the elements of the string we can use a loop and check for
the \0 null character.
 In the following example we are using while loop to print the characters of the
string variable str.

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

// string variable
char str[6] = "Hello";

// pointer variable
char *ptr = str;

// print the string


while(*ptr != '\0') {
printf("%c", *ptr);
// move the ptr pointer to the next memory location
ptr++;
}
return 0;
}

Using pointer to store string


 We can achieve the same result by creating a character pointer that points at a
string value stored at some memory location.
 In the following example we are using character pointer variable strPtr to store
string value.

#include <stdio.h>
int main()
{
// pointer variable to store string
char *strPtr = "Hello";

// temporary pointer variable


char *t = strPtr;

// print the string


while(*t != '\0')
{
printf("%c", *t);
// move the t pointer to the next memory location
t++;
}

return 0;
}

Note!
In the above code we are using another character pointer t to print the characters of the
string as because we don't want to lose the starting address of the string "Hello" which
is saved in pointer variable strPtr.
 In the above image the string "Hello" is saved in the memory location 5000 to 5005.
 The pointer variable strPtr is at memory location 8000 and is pointing at the string
address 5000.
 The temporary variable is also assigned the address of the string so, it too holds the
value 5000 and points at the starting memory location of the string "Hello".

*********

You might also like