Unit – 9
POINTERS
The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. ... int n = 10; int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
One of the vital and heavily used feature ‘C’ is pointer. Most of the other programming languages also support pointers but only few of them use it freely. Support pointers but only few of them use it freely.
When we declare any variable in C language, there are three things associated with that variable.
1. Data type of variable : Data type defines the type of data that variable can hold. Data type tells compiler about the amount of memory allocate to the variable.
2. Address of Variable : Address of variable represent the exact address of memory location which is allocated to variable.
3. Value of variable : It is the value of variable which is store at the address of memory location allocated to variable.
Example : int n = 5;
In the above example ‘int’ is the data type which tells compiler to allocate 2 bytes of memory to variable ‘n’.
Once the variable is declare compiler allocated two bytes of memory to variable ‘n’. Suppose the address of that memory location is 1020. At the address of memory location 1020 the value 5 is store.
Memory map for above declaration is as follows.
use of &,/and ‘*’ operator
Consider the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,
printf (“Enter two numbers”);
scanf (“%d%d”, & a,&b);
c=a+b;
printf(“/n Addition is %d”, C);
printf(“/n Address of variable C is %d”, &C);
getch ();
}
Above program is the program for addition of two numbers in ‘C’ language. In the sevent instruction of above program we used operator ‘%’ and ‘&’ ‘%d’ is the access specifier which tells compiler to take integer value as a inpute whereas. ‘&a’ tells compile to store the taken value at the address of variable ‘a’.
In the ninth instruction compiler will print me value of ‘C’ so the output of 9th instruction is as follows.
Addition is 5 [Note : considering a = 2 and b = 3]
In the tenth instruction compiler will print me address of variable C.
So the output of lenth instruction is as follows. Address of variable C is 1020.
Now consider the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf(“Enter two numbers”);
scanf(“%d %d”, & a, &b);
c=a+b;
printf(“\n Addition is %d”,C);
printf(“\n Address of variable C is %d”,&C);
printf(‘\n value of variable C is %d”, *(&C));
getch();
}
Now, we all are clear about the output of instruction 9 and 10.
In the 11th instruction, operator *and & is used. ‘*’ operator tells compile to pickup the value which is stored at the address of variable C. So the output of 11th instruction is as follow. Value of variable C is 5 [considering a = 24 b = 3;]
Self -Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member.
The structures pointing to the same type of structures are self-referential in nature.
structnode {
intdata1;
chardata2;
structnode* link;
};
intmain()
{
structnode ob;
return0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before accessing, as by default it contains garbage value.
Linked List is a collection of multiple nodes. Each node is connected to other node via link or pointer. Every node consists of two fields.
- Data
- Pointer to next node.
Data |
Address of next node |
Fig.1 Structure of a node
Data Field is used to store information and Address Field stores the memory address of next node.
Fig.2 Structure of a Linked List
This Linked List consists of three nodes. First node is called as Head node. Assume that first node is stored at memory location 1000.First node stores value 2 in data field. Second node starts at memory address 2000 and hence 2000 is stored at address field of First node. Third node is located at memory location 3000 and hence 3000 is stored at address field of Second node. Same concept is used for all nodes in Linked List. Address field of last node contains NULL as last node does not point to any other node.
Types of Linked List:
- Singly Linked List
- Doubly Linked List
- Circular Linked List
We will discuss these types in more detail.
Singly Linked List
Each node in singly linked list points to next node and it appears to move in one direction. Thus SLL is unidirectional. Fig.4 shows schematic diagram of singly linked list with 4 nodes.
DOUBLY LINKED LIST:
Singly or Circular Linked List can be traversed only in forward direction since node contains only one pointer field. Node in doubly linked list contains one data field and two pointer fields.
Left link | Data | Right Link |
Fig.5 Structure of a node in DLL
Left Link points to predecessor node and right link points to successor node. Information is stored in data field. Left link of First node and Right link of last node points to NULL. These two links enable bi-directional traversing, i.e. traversing the list in backward and forward direction. Hence called as bidirectional or doubly linked list.
CIRCULAR LINKED LIST:
A circular linked list is a linked list in which last node points to first node i.e next pointer of last node points to first node. Circular linked list does not contain NULL pointers.
Here A is the first node and C is the last node. C points to A and hence C stores address of A.
Till this point we are clear about the pointer of different data types in this section we study the pointer of pointer which is also called as double pointer.
Pointer variable is responsible to hold the address of a variable but when user defines pointer to pointer variable then that variable is responsible to hold the address of pointer variable. Pointer to pointer variable is declare by putting extra asterisk sign before the pointer variable. Following is the declaration of pointer to pointer variable
Data-Type **variable-name
Data type is responsible to define type of value stored at the location of pointer variable.
Two asterisk signs indicated that it is pointer to pointer variable.
User can allocate any name to the pointer variable by following all the rules of allocating variable name.
Consider the following program
#include<stdio.h>
#include<conio.h>
void main()
{
int n=5;
int *np,**npp;
np=&n;
npp=&np;
printf("\n value of n is %d",n);
printf("\n value of n is %d",*np);
printf("\n value of n is %d",**npp);
getch();
}
Above program is basic program for double pointer which contains three ‘printf’ statements. The explanation of these statements are as follows.
1. In the first ‘printf’ statement compiler will directly print the value of variable ‘n’ which is ‘5’.
2. In the second ‘printf’ statement compiler will print the value of pointer variable ‘np’. ‘np’ variable contains the address of variable ‘n’ but as we put the asterisk sign before it so it will print the value which is present at the address of variable ‘n’ which is ‘5’
3. In the third printf statement compiler will print the value of pointer to pointer variable ‘npp’. ‘npp’ variable contains the address of pointer variable ‘np’ and ‘np’ variable contains the address of variable n’ but as we put the two asterisk signs before it so it will print the value which is present at the address of variable ‘n’ which is ‘5’. If we put only one asterisk sign the it will print the address of variable ‘n’.
User can allocate any name to the pointer variable by following all the rules of allocating variable.
Pointer is a special variable that can hold the address of another variable whereas arrays are the special type of linear data structure in which elements are stored in contiguous memory locations. Pointers to array are used to retrieve the values of array element from their location. Pointer to array means that a variable which is meant to hold the address of array element. Following is the syntax of assigning the address of array element to pointer.
pointer-name = & array-name[element];
For example:
int arr[4];
int *p;
p= &arr[1];
In the above example, pointer variable ‘p’ is pointing the address of second variable of the array ‘arr’. Following figure depict the pictorial representation of above code.
Declaring Pointer to array
User can access the elements of array by using pointer variable. If we want to store value 7 at the second position then we need to write
*p= 7;
Assigning value to second position of an array
Pointer arithmetic can be used to perform the arithmetic operation on pointer to array. There are three forms of pointer arithmetic
1.Adding an integer to a pointer: C language allows user to add integer value to the pointer variable. Suppose in the above example we can shift the pointer variable ‘p’ to the forth position by writing
p=p+2;
Now, if we write *p=9 then value ‘9’ is stored at the last position.
Adding an integer to a pointer
2.Subtracting an integer from a pointer: Similar to addition of integer to pointer, user can subtract the integer value from pointer variable. We can shift the pointer variable ‘p’ to the third position by writing
p=p-1;
Now, if we write *p=5 then value ‘5’ is stored at the third position
Subtracting an integer from a pointer
3.Subtracting one pointer from another: C language allow user to perform arithmetic operation on two pointer variables. Consider the following code
int *p,*q, r,s;
int arr[4];
arr[1]=7;
arr[2]=5;
arr[3]=9;
p=&arr[2];
q=&arr[3];
r= p-q;
s=q-p;
In the above program variable ‘r’ contains the value ‘-1’ whereas variable ‘s’ contain value ’1’.
Pointer to Single Dimensional Arrays
Single dimensional array are the data structure in which all the elements are stored in a single row. Indexing of single dimensional array starts with 0 whereas last element has index (array size-1). All the elements of the array are of similar data-types, C language does not allow user to store elements of two or more different data type in a single array. Suppose user wants to store string ‘Hello Raushan’ then initially user required character type of array. Minimum size of an array to store above string is 13 as it contains 12 alphabets and one space. A pointer variable can store the address of only one array variable at a single instant of time. Similar to array, pointer can also hold the address of only respective type of element. For the above string user required character type of pointer. Following is the syntax of declaring single dimensional array and a pointer to array.
char arr[13]= {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ’, ‘R’, ‘a’, ‘u’, ‘s’, ‘h’, ‘a’, ‘n’};
char *p;
p=&arr[0];
In the above syntax, First line represents the syntax of declaring and defining single dimensional array. Here we declare the character type of array of size 13. Total memory allocated to the ‘arr’ array is 13. This array can hold 13 elements having data type ‘char’ and all these elements are stored in the consecutive memory location. Here we are storing string ‘Hello Raushan’ to the array ‘arr’. The index of first element (ie ‘H’) is arr[0] where as the last element (ie ‘n’) is having index arr[12].
Second line represents the syntax of declaring pointer variable. Here, we define ‘p’ as a pointer variable which is of type ‘char’. This pointer variable can perform the operation on element having data type ‘char’.
Third line represents the syntax of defining pointer variable. Here, we assign the address of first element of the array ‘arr’ to pointer variable ‘p’.
Memory map of above syntax is as follows
Consider the following basic program of pointer to array
#include<stdio.h>
void main()
{
int a[]={1,2,3,5,6,7,8};
int *p= a;
printf("\n This is the address of a %u, value of &a is %u ,Address of first element %d ,
Value stored at first place is %d",a,&a,&a[0],*a);
printf("\nThis is the address at p %u , value at p %u and the value pointed by p
%d",&p,p,*p);
printf("\n");
}
Output:
This is the address of a 3219815716, value of &a is 3219815716 ,Address of first element 3219815716 , Value stored at first place is 1
This is the address at p 3219815712 , value at p 3219815716 and the value pointed by
p 1
Consider the following program
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[3];
int *p;
arr[0]=3;
arr[1]=6;
arr[2]=8;
for(i=0;i<3;i++)
{
p= &arr[i];
printf(“address of %d element is”,p);
printf(“\t value of %d element is \n”,*p);
}
In the above program, we define the array of size 3 in which value of first element of the array is 3, second element has value 6 and last element has value 8.Integer type of pointer variable ‘p’ initially points to the first element of the array. So, first ‘printf’ statement is responsible to print the address of array element whereas second ‘printf’ statement is used to print the value of array element using pointer.
For the first iteration of ‘for’ loop, value of loop variable ‘I’ is ‘0’. So, pointer variable ‘p’ contains the address of first element of the array ‘arr’. First ‘printf’ statement will print the memory address of first element of the array and second ‘printf’ statement print the value of first element of the array ie ‘3’.
In the second iteration loop variable is incremented by one. Now, ‘p’ contains the address of second element of the array ie ‘arr[1]’. So, this time ‘printf’ statements prints the address and value of second element of the array.
In the third iteration loop variable is incremented by one and it becomes ‘2’. Now, ‘p’ contains the address of third element of the array ie ‘arr[2]’. So, this time ‘printf’ statements prints the address and value of third element of the array.
Again the value of loop variable is incremented by one and it becomes ‘3’. So, the condition inside ‘for’ loop is not satisfied and flow of program execution comes out of loop.
Pointer to Multidimensional Arrays
In multidimensional array all the elements of the array are stored in multiple stacks of rows. Two dimensional array has two stacks of rows, it looks like two dimensional matrix containing rows and columns. Three dimensional array has three stacks of rows and it looks like a rubik’s cube. Like single dimensional array, all the elements of multidimensional array are of same type and C language does not allow user to store elements of two or more different data type in a single multidimensional array.
Suppose user wants to store string ‘Hello Raushan’ in two dimensional array, minimum size of an array to store above strings is 13 as it contains 12 alphabets and one space. Two dimensional arrays are built with rows and columns. For the above string we need to divide total array size into rows and columns. A pointer variable can store the address of only one array variable at a single instant of time. Similar to array, pointer can also hold the address of only respective type of element. For the above string user required character type of pointer. Following is the syntax of declaring two dimensional array and a pointer to array.
char arr[2][7]= {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ’, ‘R’, ‘a’, ‘u’, ‘s’, ‘h’, ‘a’, ‘n’};
char *p;
p=&arr[0][0];
In the above syntax, First line represents the syntax of declaring and defining two dimensional array. Here we declare the character type of array of size 14, which is divided into two rows and seven columns. Total memory allocated to the ‘arr’ array is 14. This array can hold 14 elements having data type ‘char’ and all these elements are stored in the consecutive memory location. Out of 14 elements the first 7 elements are stored in the first row whereas remaining elements are stored in the second row. The index of first element (ie ‘H’) is arr[0][0] where as the last element (ie ‘n’) is having index arr[1][5]. At the last position of the array ie arr[1][6] contains garbage value.
Second line represents the syntax of declaring pointer variable. Here, we define ‘p’ as a pointer variable which is of type ‘char’. This pointer variable can perform the operation on element having data type ‘char’.
Third line represents the syntax of defining pointer variable. Here, we assign the address of first element of the array ‘arr’ to pointer variable ‘p’.
Memory map of above syntax is as follows
Consider the following program
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[2][3],i,j,*p;
clrscr();
printf("enter the elements of array");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&arr[i][j]);
}
}
printf("Two dimensional array is\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\t %d",arr[i][j]);
}
printf("\n");
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
p=&arr[i][j];
printf("\n address is %d and value is %d",p,*p);
}
}
getch();
}
Output:
Enter the elements of array
4
5
6
1
2
3
Two dimensional array is
4 5 6
1 2 3
address is -24 and value is 4
address is -22 and value is 5
address is -20 and value is 6
address is -18 and value is 1
address is -16 and value is 2
address is -14 and value is 3
In the above program, we define the array of size 6 which is divided in to two rows and three columns. in which value of first element of the array is 4 which is stored at location of arr[0][0], second element has value 4, which is stored at location of arr[0][1]and last element has value 3, which is stored at location of arr[1][2].
In ‘C’ language we can store string in the array of character. Array of character holding string is terminated by null character (‘\0’). C language treats ‘’\0’’ as a one character. ‘\0’ represents the end og the string and also return logical false value. Each element in the array of character requires one byte of memory storage. User can define string constant by putting all the characters of string in a pain of double quotes. C compiler automatically adds ‘\0’ at the end of every string. There are two ways to initialize the string
1. Initialize the string by using array
char array_name[size]={‘a1’, ‘a2’,…..’an’, ‘\0’};
Example: char arr[7]={‘H’, ’e’, ‘l’, ’l’, ’o’, ‘\0’};
2. Initialize the string constant by using array
char array_name[size]=”string”;
Example: char arr[7]=”Hello”
In the above syntax, ’C’ compiler automatically introduce ‘\0’ at the end of the string. Array size is not the compulsory factor in the string initialization. User is free to define unsized character array. In unsized character array compiler will calculate the length of string and allocate the required memory space to the array of characters
3. Initialize the string constant by using pointer
char *pointer_name;
pointer_name = “string”;
Example:
char *ptr;
ptr =”Hello”;
Consider the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[] = {'F','i', 'r', 's', 't','\0'};
char str2[] = "Second";
char *ptr;
int i;
clrscr();
for (i=0; str1[i]; i++)
printf("%c", str1[i]);
printf("\n");
for (i=0; str2[i]; i++)
printf("%c", str2[i]);
printf("\n");
ptr = "Third Sring with pointer";
for (i=0; *ptr; i++)
printf("%c", *ptr++);
getch();
}
Output of above program is
First
Second
Third string with pointer
In the above program we used two charater array of name str1 and str2. str1 array contains the set of characters including null character whereas array str2 contains the string constant. Both the arrays are unsized so compiler automatically calculates the size and assign required amount of memory to arrays. We also deused character pointer ‘ptr’ and assign the value ‘Third string with pointer’ to the pointer ‘ptr’. ‘ptr’ initially pointes to the first letter of the string ie’T’, so inprintf statement we used ‘*ptr++’which is responsible to move the pointer variable to the next element of the string.
As we know pointer is variable which holds the address of another variable whereas pointer to string holds the address of first element of the string. Pointer is the easiest way to manipulate string. With the help of pointer user can manipulate the string on the basis of address of memory location of the string elements.
If we want to modify the third string in the above program ie ‘Third string with pointer’ in such a way that elements storing at the even address will follow ‘$’ sign whereas odd address elements are remain unchanged. For this modification first of all we need to find address location of first element, if it is odd then we need to print ‘$’ sign before second element. As each element in the string require only one byte of memory so the address of next element will be even if address of first element is odd and vice-versa. Consider the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[] = {'F','i', 'r', 's', 't','\0'};
char str2[] = "Second";
char *ptr;
int i,n;
clrscr();
for (i=0; str1[i]; i++)
printf("%c", str1[i]);
printf("\n");
for (i=0; str2[i]; i++)
printf("%c", str2[i]);
printf("\n");
ptr = "Third Sring with pointer";
for (i=0; *ptr; i++)
{
if(i==0)
{
printf("address of first element ie %c is %d\n",*ptr,ptr);
printf("\n Modified string is as follows\n");
}
printf("%c\t", *ptr++);
n=ptr;
if(n%2==0)
printf("$");
}
getch();
}
Output of above program is
First
Second
Address of first element ie T is 193
Modified string is as follows
T | $h | I | $r | d | $ | S | $t | r | $i | n | $g |
$w | I | $t | h | $ | p | $o | i | $n | T | $e | r |
Similar to array of character, integer C language also provides facility to create array of pointers. Array of pointers contains same type of pointer variables which are stored in the consecutive memory location. As pointer variables are responsible to store addresses, array of pointer is also called as the collection of addresses. Array of pointer is different from the pointer to array. In pointer to array, a single pointer pointes to all the elements of an array. In array of pointers, all the elements of array are pointed by pointers. Syntax of declaring array of pointer is
data_type *array_name[size].
Consider the following program
#include<stdio.h>
int main(void)
{
char *p1 = "Sonu";
char *p2 = "Rani";
char *p3 = "Debu";
char *arr[3];
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;
printf("\n p1 = [%s] \n",p1);
printf("\n p2 = [%s] \n",p2);
printf("\n p3 = [%s] \n",p3);
printf("\n arr[0] = [%s] \n",arr[0]);
printf("\n arr[1] = [%s] \n",arr[1]);
printf("\n arr[2] = [%s] \n",arr[2]);
return 0;
}
In the above code, we declare three pointers pointing to three strings. Then we declared an array of three pointers and assigned the pointers ‘p1′, ‘p2′ and ‘p3′ to the 0, 1 and 2 index of array. Compiler first assign memory address to three pointer variables and the array of pointers and then store the value at the respective address of pointer variable and array element. Diagrammatic representation of the memory mapping to above code is as follows.
Element | Memory address | Value |
P1 | -28 | Sonu |
P2 | -30 | Rani |
P3 | -32 | Debu |
Arr[0] | -38 | Sonu |
Arr[1] | -36 | Rani |
Arr[2] | -34 | Debu |
Let’s see the output:
p1 = [Sonu]
p2 = [Rani]
p3 = [Debu]
arr[0] = [Sonu]
arr[1] = [Rani]
arr[2] = [Debu]
Pointer to function is the very important concept in C language. With the help of pointer to function user can access the several different functions on the basis of input data. Function in C language is used to improve reusability of the code. With the help of function user can use the same sample of code for the multiple times. The process of debugging and error correction is also easier with the help of function. Functions divide the complete program into several different modules. Syntax for defining function is as follows
Syntax : Data_type Function_name();
Example: # int fun ( ) ;
In the above syntax ‘fun’ is the function name which is of type integer. The function name ‘fun’ is also work as pointer variable to function. But it is the constant pointer variable so it is illegal to assign value to ‘fun’. Following program illustrate the syntax and use of function
#include<stdio.h>
#include<conio.h>
void sayhi()
{
printf("hi everyone");
}
void main()
{
clrscr();
sayhi();
getch();
}
Output of above program is as follows
hi everyone
In the above program we create function ‘sayhi’ and use it directly into the main function. Now we will see how to declare pointer to function. Pointer variable name should followed by asterisk sign. Syntax for declaring pointer to function is as follows.
Syntax : Data_type (*pointer_name)();
Example : int (*ptr)();
In the above example we declare pointer variable ‘ptr’ which is responsible to hold the pointer to a function and return an int. Pointer name should be enclosed with the parenthesis as lack of parenthesis pointer variable returns pointer to an int. Following program illustrate the syntax and use of pointer to function
#include<stdio.h>
#include<conio.h>
void sayhi()
{
printf("hi everyone");
}
void main()
{
void(*sayhiptr)()=sayhi;
clrscr();
(*sayhiptr)();
getch();
}
Output of above program is as follows
hi everyone
In the above program we create function ‘sayhi’ and pointer to function ‘sayhiptr’. The function will not return anything so return type is void. Name of function works as a pointer to function and contains the address of function. So, we assign it to the pointer variable. At last line we call function with the help of pointer.
Function Pointer with Parameter:
Like routine function call, user is also allowed to send pameter with the function pointer.
Consider the following program of passing three integer type parameters to function with the help of function pointer.
#include<stdio.h>
#include<conio.h>
void total(int m1,int m2, int m3)
{
int result=m1+m2+m3;
printf("\n Total marks is %d",result);
}
void main()
{
int m1,m2,m3;
void (*totalptr)()=total;
clrscr();
printf("Enter the marks of three subjects");
scanf("%d %d %d", &m1,&m2,&m3);
(*totalptr)(m1,m2,m3);
getch();
}
Output of above program is as follows
Enter the marks of three subjects
25
35
30
Total marks is 90
In the above program we create function ‘total’ which accept three integer type values from the main function. void (*totalptr)()=total; line is responsible to declare and define pointer to function variable. Whereas line(*totalptr)(m1,m2,m3); is used to call function with the help of pointer.
A pointer to structures is where a pointer variable can point to the address of a structure variable. Here is how we can declare a pointer to a structure variable.
1 2 3 4 5 6 7 8 9 10 11 12 | struct dog { char name[10]; char breed[10]; int age; char color[10]; };
struct dog spike;
// declaring a pointer to a structure of type struct dog struct dog *ptr_dog |
This declares a pointer ptr_dog that can store the address of the variable of type struct dog. We can now assign the address of variable spike to ptr_dog using & operator.
1 | ptr_dog = &spike; |
Now ptr_dog points to the structure variable spike.
Accessing members using Pointer
There are two ways of accessing members of structure using pointer:
- Using indirection (*) operator and dot (.) operator.
- Using arrow (->) operator or membership operator.
Using indirection (*) operator and dot (.) operator
At this point ptr_dog points to the structure variable spike, so by dereferencing it we will get the contents of the spike. This means spike and *ptr_dog are functionally equivalent. To access a member of structure write *ptr_dog followed by a dot(.) operator, followed by the name of the member.
For example:
(*ptr_dog).name – refers to the name of dog
(*ptr_dog).breed – refers to the breed of dog
Parentheses around *ptr_dog are necessary because the precedence of dot(.) operator is greater than that of indirection (*) operator.
Using arrow (->) operator or membership operator.
To access members using arrow (->) operator write pointer variable followed by -> operator, followed by name of the member.
ptr_dog->name - refers to the name of dog
ptr_dog->breed - refers to the breed of dog
We can also modify the value of members using pointer notation.
| strcpy(ptr_dog->name, "new_name");
In the above expression precedence of arrow operator (->) is greater than that of prefix decrement operator (--), so first -> operator is applied in the expression then its value is decremented by 1. #include<stdio.h>
struct dog { char name[10]; char breed[10]; int age; char color[10]; };
int main() { struct dog my_dog = {"tyke", "Bulldog", 5, "white"}; struct dog *ptr_dog; ptr_dog = &my_dog;
printf("Dog's name: %s\n", ptr_dog->name); printf("Dog's breed: %s\n", ptr_dog->breed); printf("Dog's age: %d\n", ptr_dog->age); printf("Dog's color: %s\n", ptr_dog->color);
// changing the name of dog from tyke to jack strcpy(ptr_dog->name, "jack");
// increasing age of dog by 1 year ptr_dog->age++;
printf("Dog's new name is: %s\n", ptr_dog->name); printf("Dog's age is: %d\n", ptr_dog->age);
// signal to operating system program ran fine return 0; } Expected Output: 1 2 3 4 5 6 7 8 9 Dog's name: tyke Dog's breed: Bulldog Dog's age: 5 Dog's color: white
After changes
Dog's new name is: jack Dog's age is: 6
|
Reference
- Brian W. Kernighan And Dennis M. Ritchie, The C Programming Language, Prentice Hall Of India
- Yashwant Kanetkar, Let Us C, Bpb Publication