0% found this document useful (0 votes)
3 views36 pages

PC U4 2024

The document covers the concepts of structures and pointers in C programming, including definitions, declarations, initialization, and features of structures. It explains the differences between structures and arrays, the use of self-referential structures, and the advantages of using pointers. Additionally, it provides syntax examples, dynamic memory allocation functions, and a sample program demonstrating the use of structures to manage student information.

Uploaded by

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

PC U4 2024

The document covers the concepts of structures and pointers in C programming, including definitions, declarations, initialization, and features of structures. It explains the differences between structures and arrays, the use of self-referential structures, and the advantages of using pointers. Additionally, it provides syntax examples, dynamic memory allocation functions, and a sample program demonstrating the use of structures to manage student information.

Uploaded by

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

Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

UNIT IV - Structure and Pointers

Structure Introduction – Structure definition – Structure declaration – Structure within


a structure –Self Referential Structure. Pointers - Definition – Initialization – Pointers
arithmetic – Pointers and arrays -Pointer to Function –Pointer and Structure- Simple programs.

2- MARKS

1. Define Structure in C. ( APR/MAY 2015)

C supports a constructed data type known as structures, a mechanism for packing data
of different types. A structure is a convenient tool for handling a group of logically related data
items. This is known as Structure.

2. Write the rules for declaring a structure.

• A structure must end with a semicolon.

• Usually a structure appears at the top of a program.

• Each element of structure must be terminated.

• The structure variable must be accessed by using dot (.) operator

3. Write the rules for initializing structure.

• The individual data members of structure cannot be initialized.

• The structure variables can be initialized at compile time only.

• The order of data members in a structure must match the order of values in enclosed
brackets.

• We can initialize only some of the data members of the structure.

• The uninitialized data members can be initialized by default with zero for int and float ‘\0’ for
character and strings.

4. What is mean by nested structure?

It is otherwise known as structure within structure, i.e., a structure appear within another
structure. This is called nested structure.

5. Write the features of Structure. (Jan. 2011)

The values of a structure variable can be assigned to another structure variable of the same
type using the assignment operator. It is not necessary to copy the structure elements.

6. How does a structure differ from an array? ( Jan 2010)


Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

Arrays Structures

1. An array is a collection of 1. Structure can have elements of


related data elements of same different types
type.

2. An array is a derived data type 2. A structure is a programmer-


defined data type

3. Any array behaves like a built-in 3. But in the case of structure, first
data types. All we have to do is to we have to design and declare a data
declare an array variable and use structure before the variable of that
it. type are declared and used.

7. Give syntax for Structure declaration.

struct structure_name

Structure_member 1;

Structure_member 2;

…….

Structure_member n;

}; v1,v2,…,vn;

8. Write short notes on self referential structures.

Self referential structures are those structures that contain a reference to data of its

same type. That is it contains the pointer to the data that is of same type of as that of the

structure.

struct node

int val;

struct node *next;

};

Here the structure node will contain two types of data- an integer val and next that is a
pointer

to a node.

Give an example where a structure data type may be required.


Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

A Structure is a collection of one or more variables possibly of different data types


grouped together under a single name for convenient handling.

struct books
{
char book_name[50];
int pages;
float price;
}b1;

9. What is a user – defined data type? (MAY-2014)


C supports the features “typedef” that allows users to define the identifier which would
represent an existing data type. This defined data type can then be used to declare variables:

Syntax:
typedef int numbers;
eg: numbers num1,num2;

In this example, num1 and num2 are declared as int variables.


The main advantage of user defined data type is that it increases the program’s readability.

Enumerated type:

This is also a user defined data type. “Enum” is the keyword and “identifier” is the user
defined data type that is used to declare the variables. It can have any value enclosed within the
curly braces.

Syntax:

enum identifier {value1,value2, value 3,…}


For example:

enum day {January,February,March,April,..};

enum day month_st,month_end;

10. Write about nested structure?(JAN-2014)

Nesting of structures are nothing but structure within another structure (i.e., a
structure can contain one or more structures embers).

A structure may be defined and/or declared inside another structure.

struct employee

int empno;

char name[15];

struct dob

int date ,

int month,
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

int year;

} d;

}emp;

11. What is the use of structure in C. (NOV 2011)

1. It is a complex data type declaration that defines a physically grouped list of variables to
be placed under one name in a block of memory, allowing the different variables to be
accessed via a single pointer, or the struct declared name which returns the same
address.
2. For increasing the execution speed.

12. Write the syntax for declaration and initialization of structures. (JAN 2011)

Syntax:
struct structure_name
{
data type data member1;

data type data member2;


.......
.......
data type data member n;
}structure variable={list of values};
Example:
struct student //declaration
{
int rno;
char name[20];
float cgpa;
}s={10,”amirtha”,95}; //initialization

13. What is a structure variable? (MAY 2013)

struct book_bank

char bname[50];

char author[50];

int pages;

float price;

}book1;

The members of a structure themselves are not variables. They do not occupy any
memory until they are associated with the structure variables such as book1. When the compiler
comes across a declaration statement, it reserves memory space for the structure variables. It
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

is also allowed to combine both the structure definition and variables declaration in one
statement.

14. Give syntax for Structure declaration.


struct structure_name
{
Structure_member 1;
Structure_member 2;
…….
Structure_member n;
}; v1,v2,…,vn;

15. What is a pointer?


A pointer is a memory variable that stores a memory address. It can have any name that is
legal for another variable and it is declared in the same fashion like other variables but it is
always denoted by pre fixing ‘*’ operator.
Pointer Declaration: datatype * variable-name;
Example: int *x, c=5; x=&a;

16. Write the features of a pointer.


Features:
Pointers save memory space.
Execution time with the pointer is faster because data is manipulated with the address,
direct access to memory location.
The memory is accessed efficiently with the pointers.
Pointers are used with data structures.
We can access elements of any type of array irrespective if its subscript range.
Pointers are used in file handling.

17. What are the various dynamic memory allocation functions?


malloc() - Used to allocate blocks of memory in required size of bytes.
free () - Used to release previously allocated memory space.
calloc() - Used to allocate memory space for an array of elements.
realloac() - Used to modify the size of the previously allocated memory space

18. Is it better to use a macro or a function?


Macros are more efficient (and faster) than function, because their corresponding code
is inserted directly at the point where the macro is called. There is no overhead involved in
using a macro like there is in placing a call to a function. However, macros are generally small
and cannot handle large, complex coding constructs. In cases where large, complex constructs
are to handled, functions are more suited, additionally; macros are expanded inline, which
means that the code is replicated for each occurrence of a macro

19. What are the uses of Pointers?


Pointers are used to return more than one value to the function · Pointers are more
efficient in handling the data in arrays · Pointers reduce the length and complexity of the
program · They increase the execution speed · The pointers save data storage space in memory
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

20. What are * and & operators means?


‘*’ operator means ‘value at the address’ ‘&’ operator means ‘address of

21. What is dangling pointer?


In C, a pointer may be used to hold the address of dynamically allocated memory. After this
memory is freed with the free() function, the pointer itself will still contain the address of the released
block. This is referred to as a dangling pointer. Using the pointer in this state is a serious
programming error. Pointer should be assigned NULL after freeing memory to avoid this bug.

22. What is a pointer? List out the advantages of using pointer.


A pointer is a special type of variable which holds the address or location of another
variable. It is declared in the same fashion like other variables but it is always denoted by ‘*’
operator.
Example:
int a, *p;
a=5;
P=&a;
Advantages:

1. For accessing a variable that is defined outside the function.


2. For efficient handling of data tables.
3. For reducing the size and complexity of programs.
4. For increasing the execution speed.
5. For saving the storage space by using the pointer arrays for character stings.

23. Define array of pointers.

Array of pointers contain collection of address. The address may be the address of
variable or array elements. So far we have studied array of different standard data types such
as array of int, float, and character and so on.

In the same way the C language also supports array of pointers. It is nothing but a
collection of addresses. Here we store addresses of variables for which we have to declare an
array as a pointer.

24. Write a program using pointer to determine the length of a character strings?
main()
{
char *name;
int length;
char *cptr=name;
name=”DEHI”;
printf(“%s\n”,name);
while(cptr!=’\0’)
{
printf(“%c is stored at address %u\n”,*cptr,cptr);
cptr++;
}
length=cptr-name;
printf(“\nlength of the string=%d\n””,length);
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

25. What is a null pointer?


A pointer is said to be null pointer when its right value is 0. A null pointer can never
point to a valid data. For checking a pointer, if it is assigned to 0, then it is a null pointer and is
not valid.
Example:
int *a;
int *b;
b=a=0;
Here b and a become null pointers after the integer value of 0 is assigned to them.

26. Define Pointer to Pointer.

It is a variable that contains the address of another variable. Similarly another pointer
variable can store the address of this pointer variable. This is known as Pointer to Pointer.

27. What are the operators exclusively used with pointers?

1. *
2. &
3. .
4. ->

28. What are an address operator and indirection operator?

The address-of operator (&) gives the address of its operand. The indirection operator
(*) accesses a value indirectly, through a pointer. The operand must be a pointer value. The
result of the operation is the value addressed by the operand; that is, the value at the address to
which its operand points.

29. What is the output of the following program?


main( )
{
int a=8,b=4,c *p1=&a , *p2=&b;
c=*p1 * p2 - *p1/*p2+9;
printf(“%d”,c) ;

30. How is pointer arithmetic done.


A pointer in C is a variable which is used to store the memory address which is a
numeric value. The arithmetic operations on pointer variable effects the memory address
pointed by pointer.
Example
int* i;
i++;
Note: pointer will be of 2 bytes. And when we increment it, it will increment by 2 bytes
because int is also of 2 bytes
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

PART -C
1. EXPLAIN ABOUT STRUCTURE WITH EXAMPLE PROGRAM. (May 2017, Jan
2014,May-2019]

DEFINITION

It is a user defined data type. A structure is a collection of variables of different types


grouped together under a single name. By using structures we can make a group of variables,
arrays, pointers and etc..,

DECLARATION OF STRUCTURES

It contains data members and each is accessed by the structure variable. A structure is
declared using the keyword struct followed by a structure name. All the variables of the
structures are declared within the structure.

Syntax:
struct structure_name

structure_element 1;

structure_element 2;

--------

--------

structure_element n;

};struct structure_name v1,v2,…,vn;

struct student
Example:
{

int marks;

float avg;

char grade;

};

The structure definition does not allocate any memory. Structure provides a model of how the
structure is to be in memory and gives details of the member names. Memory is allocated for
the structure when we declare a variable of the structure.
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

struct student

int marks;

float avg;

char grade;

}s; // Declaring Structure Variable

Memory allocation for above structure is

2000 2001 2002 2003

int marks

float avg

avg grade

INITIALIZATION OF STRUCTURES

Initializing a structure means assigning some constants to the members of the structure. The
initializes are enclosed in braces and are separated by commas.

Example:

struct student

int r_no;

char name[20];

char course[20];

float fees;

}struct student stud1 = {01, “Rahul”, “IT”, 45000};

ACCESSING THE MEMBERS OF A STRUCTURE

Array elements are accessed using the Subscript variable, Similarly Structure members are
accessed using dot [.] operator. It is called as “Structure member Operator”. Use this Operator
in between “Structure name” & “member name”
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

Syntax:

struct_var.member_name;

Example:

stud1.rno = 01;

strcpy(stud1.name, “Kalam”);

stud1.course = “IT”;

stud1.fees = 45000;

Here the dot is an operator which selects a member from a structure.

Selecting a member from a structure pointer happens frequently, it has its own operator
-> which acts as follows. Assume that stud1 is a pointer to a structure of type student we would
refer to the name member as

stud1.rno->name

PROGRAM USING STRUCTURES TO READ AND DISPLAY THE INFORMATION ABOUT A


STUDENT

#include<stdio.h>

#include<conio.h>

struct student

int rollno;

char name[80];

float fees;

char DOB[80];

};

int main()

{
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

struct student stud1;

clrscr( );

printf(“\n Enter the roll number : “);

scanf(“%d”, &stud1.rollno);

printf(“\n Enter the name : “);

scanf(“%s”, stud1.name);

printf(“\n Enter the fees : “);

scanf(“%f”, &stud1.fees);

printf(“\n Enter the DOB : “);

scanf(“%s”, stud1.DOB);

printf(“\n ********STUDENT’S DETAILS *******”);

printf(“\n ROLL No. = %d”, stud1.rollno);

printf(“\n NAME. = %s”, stud1.name);

printf(“\n ROLL No. = %f”, stud1.fees);

printf(“\n ROLL No. = %s”, stud1.DOB);

getch( );

OUTPUT:

Enter the roll number : 101

Enter the name : rahul

Enter the fees : 45000

Enter the DOB : 11.2.1995

********STUDENTÆS DETAILS *******

ROLL No. = 101

NAME. = rahul

ROLL No. = 45000.000000

ROLL No. = 11.2.1995


Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

2 DISCUSS ABOUT ARRAYS OF STRUCTURES WITH EXAMPLE. Nov 2016, May 2016,
Jan 2016, May 2015, Jan 2013,May-2019)

ARRAYS OF STRUCTURES

An array of structures is the same way as we declare an array of built-in data type. The
array of structures can be used when common structure definition is need for the process of
information.

Syntax

struct struct_name struct_var[index];

Example

struct student stud[30];

Now, to assign values to the ith student of the class, we will write,

stud[i].r_no = 09;

stud[i].name = “RAM”;

stud[i].course = “CSE”;

stud[i].fees = 60000;

/*program to read and display information of all the students in the class*/(May-
2019)

#include<stdio.h>
#include<conio.h>

struct studentinfo
{
int roll;
char name[20];
int age;
};
void main()
{

struct studentinfo s[100];

clrscr();
int n,i;
printf("\nHow many students information do you want to enter?");
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

scanf("%d",&n);
printf("Enter Student Information:");
for(i=1;i<=n;i++)
{
printf("\nEnter Roll no.:");
scanf("%d",&s[i].roll);
printf("\nEnter the name of the student:");
scanf("%s",&s[i].name);
printf("\nEnter the age of the student:");
scanf("%d",&s[i].age);
}
printf("\n\nInformation of all studenst:");
for(i=1;i<=n;i++)
{
printf("\nRoll no.:%d",s[i].roll);
printf("\nName:%s",s[i].name);
printf("\nAge of student:%d\n\n",s[i].age);
}
getch( );

3: ARRAYS WITHIN STRUCTURES

C permits the use of arrays as structure members. We have already used arrays of
characters inside a structure. Similarly, we can use single-dimensional or multidimensional
arrays of type int or float. For example, the following structure declaration is valid:

struct marks

int number;

float subject[3];

} student[2];

Here the member structure subject contains three elements, subject[0], subject[1],
subject[2]. These elements can be accessed using appropriate subscripts. For example, the
name, student[1].subject[2];

would refer to the marks obtained in the third subject by the second student.

Example: ARRAYS WITHIN A STRUCTURE


Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

Univ. Ques. May 2014


main()

struct marks

int sub[3];

int total;

};

struct marks student[3] = {45,67,81,0,75,53,69,0,57,36,71,0};

struct marks total;

int i,j;

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

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

student[i].total += student[i].sub[j];

total.sub[j] += student[i].sub[j];

total.total += student[i].total;

printf("STUDENT TOTAL\n\n");

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

printf("Student[%d] %d\n", i+1, student[i].total);

printf("\nSUBJECT TOTAL\n\n");

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

printf("Subject-%d %d\n", j+1, total.sub[j]);

printf("\nGrand Total = %d\n", total.total);


Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

Output:

STUDENT TOTAL

Student[1] 193

Student[2] 197

Student[3] 164

SUBJECT TOTAL

Subject-1 177

Subject-2 156

Subject-3 221

Grand Total = 554

4. EXPLAIN ABOUT STRUCTURE WITHIN STRUCTURE WITH EXAMPLE PROGRAM.

[ Univ. Ques. Jan 2016, May 2015, Jan 2015, May 2013]

NESTED STRUCTURES

A structure can be placed within another structure. That is, a structure may contain another
structure as its member. Such a structure that contains another structure as its member is
called a nested structure.

Example:

/*Program to read and display the information of student using nested


Structure*/

#include<stdio.h>

#include<conio.h>

struct DOB

int day;

int month;
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

int year;

};

struct student

int roll_no;

char name[100];

float fees;

struct DOB date;

};

int main( )

struct student stud;

clrscr( );

printf(“\n Enter the roll number : “);

scanf(“%d”, &stud.roll_no);

printf(“\n Enter the name : “);

scanf(“%s”, stud.name);

printf(“\n Enter the fees : “);

scanf(“%f”, &stud.fees);

printf(“\n Enter the DOB : “);

scanf(“%d %d %d”, &stud.date.day,&stud.date.month,&stud.date.year);

printf(“\n ********STUDENT’S DETAILS *******”);

printf(“\n ROLL No. = %d”, stud.roll_no);

printf(“\n NAME. = %s”, stud.name);

printf(“\n FEES. = %f”, stud.fees);

printf(“\n DOB = %d - %d - %d”, stud.date.day, stud.date.month,stud.date.year);

getch( );

}
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

OUTPUT:

Enter the roll number : 101

Enter the name : rahul

Enter the fees : 45000

Enter the DOB : 11.2.1995

********STUDENTÆS DETAILS *******

ROLL No. = 101

NAME. = rahul

ROLL No. = 45000.000000

ROLL No. = 11.2.1995

5: STRUCTURE AND FUNCTIONS

Univ. Ques. May 2014, May 2013

Similar to arrays and pointers a structure can also be passed to a function. There are
three ways of passing a structure to a function.

They are;

1. Passing a structure member to functions.


2. Passing the address of member to functions.
3. Passing entire structure to functions.

1. PASSING A STRUCTURE MEMBER OF FUNCTIONS

 This method is used to pass each member of the structure as an actual argument of
the function call statement.
 When you pass a member of a structure to a function as an argument, you are
actually passing the value of that member to the function.
 The arguments are then treated independently as ordinary variables.
 For example;

struct employee

int empno;

char empname[20];
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

float salary;

} emp;

 The member of the structure can be passed to the function employ() as

 employ(emp.empno)
 employ(emp.empname)
 employ(emp.salary);

 Where employ(emp.empno) passes the integer value of empno to the function employ().

 Employ(emp.empname[1]) passes the character value empname to the function


employ().
 Similarly employ(emp.salary) passes the float value of salary to the function employ().

 This method is the most common method and becomes inefficient when the structure is
large.

2. PASSING THE ADDRESS OF MEMBER TO FUNCTIONS

 The member of a structure can also be passed to function by passing the address of
the members.

 In this, a method the address location of the members is passed to the called
function, hence the address operator (&) is used before the structure name.

 The member of the structure can be passed to a function employ() as

employ(&emp.empno); // passes the address of integer value of empno

to the function employ().

employ(&emp.salary);

employ(&emp.empname); // note that the address operator is not used


since

the variable empname is a string.

3. PASSING ENTIRE STRUCTURE TO FUNCTIONS


In this method, the entire structure is passed as an argument to the function, since the
function is working on a copy of the structures, any changes made to the structure members
within the function are not reflected in the original structure. Therefore, it is necessary for the
function to return the entire structure back to the calling function.

Example: /* Function struct.c */


Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

#include<stdio.h>

void employ(struct employee emp);

struct employee

int empno;

char empname[20];

};

main()

struct employee emp1;

printf(“\nEnter Employee No. and Name : “);

scanf(“%d%s”,&emp1.empno,emp1.empname);

employ(emp1);

void employ(struct employee emp)

printf(“\nThe Employee No. is : %d”, emp.empno);

printf(“\nThe Employee Name is : %s”, emp.empname);

OUTPUT:

Enter Employee No. and Name : 101 David

The Employee No. is : 101

The Employee Name is : David

Example: STRUCTURES AS FUNCTION PARAMETERS

/* Passing a copy of the entire structure */

struct stores

{
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

char name[20];

float price;

int quantity;

};

struct stores update (struct stores product, float p, int q);

float mul (struct stores stock);

main()

float p_increment, value;

int q_increment;

struct stores item = {"XYZ", 25.75, 12};

printf("\nInput increment values:");

printf(" price increment and quantity increment\n");

scanf("%f %d", &p_increment, &q_increment);

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

item = update(item, p_increment, q_increment);

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

printf("Updated values of item\n\n");

printf("Name : %s\n",item.name);

printf("Price : %f\n",item.price);

printf("Quantity : %d\n",item.quantity);

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

value = mul(item);

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

printf("\nValue of the item = %f\n", value);

struct stores update(struct stores product, float p, int q)

{
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

product.price += p;

product.quantity += q;

return(product);

float mul(struct stores stock)

return(stock.price * stock.quantity);

Output:

Input increment values: price increment and quantity increment

10 12

Updated values of item

Name : XYZ

Price : 35.750000

Quantity : 24

Value of the item = 858.000000

6: SELF-REFERENTIAL STRUCTURES(Pointers and Structure)

Self referential structures are those structures that contain a reference to data of its same
type. That is, a self referential structure in addition to other data contains a pointer to a data
that is of the same type as that of the structure. For example, consider the structure node given
below.

struct node

int item;

struct node *next;

};

Here the structure node will contain two types of data- an integer item and next that is a

pointer to a node. Self-referential structure is the foundation of other data structures. They are
most commonly used in linked list data structure implementation
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

Example:

#include <stdio.h>

#include<conio.h>

struct stud

int roll;

char name[30];

int age;

struct stud *next; // self reference structure

void main()

struct stud n1, n2, n3;

struct stud *p;

clrscr( );

printf("Enter the details of students");

scanf ("%d %s %d", &n1.roll, n1.name, &n1.age);

scanf ("%d %s %d", &n2.roll, n2.name, &n2.age);

scanf ("%d %s %d", &n3.roll, n3.name, &n3.age);

n1.next = &n2; //assigning address of the structure

n2.next = &n3;

n3.next = NULL;

p = &n1; /* point to 1stelement */

printf(“\n The students details are:”);

while (p != NULL)

printf ("\n %d %s %d", p->roll, p->name, p->age);

p = p->next;

getch( );
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

OUTPUT:

Enter the details of students

101 ram 19

102 raj 19

103 rahul 18

The students details are:

101 ram 19

102 raj 19

103 rahul 18

15

Explanation:

The list consists of three nodes n1, n2 and n3 by declaring struct stud n1, n2, n3. To create

the links between nodes, we write n1.next = &n2; n2.next = &n3; By pointing the address of
the first element, and while loop we can traverse through the nodes and display the student
details.

7: SIZE OF STRUCTURES

We normally use structures, unions and arrays to create variables of large sizes. The
actual size of these variables in terms of bytes may change from machine to machine. We may
use the unary operator sizeof to tell us the size of a structure (or any variable). The expression

sizeof(struct x)

we evaluate the number of bytes required to hold all the members of the structure x. If y is a
simple structure variable of type struct x, then the expression

sizeof(y)

would also give the same answer. However, if y is an array variable of type struct x, then

sizeof(y)

would give the total number of bytes the array y requires.

This kind of information would be useful to determine the number of records in a


database. For example, the expression

sizeof(y)/sizeof(x)

would give the number of elements in the array y


Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

8: USER –DEFINED DATA TYPES

TYPEDEF

C provides a capability that enables the programmer to assign an alternate name to a


data-type. This is done with a statement known as typedef.

Syntax: typedef type dataname;

Description typedef - keyword.

type – data-type

dataname – specifies the user defined name for that type.

Example: typedef int weeks;

(Here weeks is the another name for int)

EXAMPLE PROGRAM FOR TYPEDEF:

Example: C Program to create user defined data type weeks on int data type
and used it in the program.

#include<stdio.h>

#define D 7

void main

typedef int weeks;

weeks wk;

printf(“Enter weeks: ”);

scanf(“%d”, &wk);

printf(“Number of days = %d”, wk*D);

Output:

Enter weeks: 4

Number of days = 28
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

ENUMERATED DATA TYPE:

 The enumerated data type is a user-defined data type.


 An enumeration is a set of named integer constants represented by identifier that
specifies all the legal values a variable of that type may have.
 Enumerated data type is declared using the enum keyword.

Syntax: enum tag{ member1, member2, …...member n };

Example: enum months{ January, February, march……December};

 enum is the key word,


 tag is the name that identifies enumeration having the
composition in the format.
Description  member1, member2, …...member n are the individual
identifiers (known as enumeration constants) that may
be assigned to the variables of this type.

9. Explain the concept of pointers in c programming

Pointer:
INTRODUCTION

The Pointer is a variable that store the address of the another variable. Pointers can be
used to access and manipulate data stored in the memory. This is known as Pointers.

It is a derived data type in C language.

Syntax:

data_type *Pointer_varaible;

Example:

int *a;

float *b;

char *c;
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

Explanation

int rno=40;

rno
Variable
40

2005 Value

Address

Let as assume that the system has assign the address location as 2005 for a variable ‘sno’.

FEATURES OF POINTERS

 Pointers are efficient in handling data.


 Pointers are used for saving memory space.
 Pointers reduce the length and complexity of the program.
 The execution time is faster.
ADVANTAGES OF POINTERS

 Pointers are more compact and efficient code.


 Pointers can be used to achieve clarity and simplicity.
 Pointers are used to pass information between function and its reference point.
 Pointers enable us to access the memory directly.

ACCESSING VARIABLE THROUGH POINTERS (2 Mark)

Once the pointer is declared and assigned to the address of another variable, the variable
can be accessed through its pointers. This is done by using another unary operator * (asterisk),
usually known as the indirection operator or dereferencing operator.

Example:

int *a;

b=25;

a=&x;

Here, ‘a’ is a pointer variable that store address of ‘b’ variable.


Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

Program:

#include<stdio.h>

#include<conio.h>

main ( )

int a=22, int *a;

clrscr();

a=&a;

printf ("\n Value of a=%d", *a);

printf ("\n Address of a=%u", &a);

printf ("\n Value at address %u=%d", &a, *(&a));

Output:

Value of a=22

Address of a=4000

value at address 4000=22

INITIALIZING POINTER VARIABLE

The process of assigning the address of a variable to a pointer variable is known as


initialization. The ampersand (*) is an address operator, which is used to access the address of
a variable and assign it to a pointer to initialize it.

Example:

P=&n;

Where ‘p’ contains the address of variable ‘n’.

10. POINTERS AND ARRAYS Jan 2016, May 2013,14


Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

When users declare an array the consecutive memory locations are located to the array
of elements. The elements of an array can be efficiently accessed by using pointers.

Example:

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

Here, ‘a’ has 5 elements.

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

10 20 30 40 50 value

2000 2002 2004 2006 2008 address

 The base address of the array starts with 0th element of the array. The array is in integer
type.
 The integer will have 2 bytes.
 The address of the next address element is incremented by 2.
Program:

/* Program to add the sum of number using pointer * / (AU-MAY/JUNE 2014)

#include<stdio.h>

main( )

int i,total,a[5],*c;

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

printf("\nEnter the number %d:”,i+1);

scanf("%d",&a[i]);

}
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

c=a;

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

total=total+*c;

c=c+1;

printf("\n Total=%d",total);

Output:

Enter the number 1:10

Enter the number 2:20

Enter the number 3:30

Enter the number 4:40

Enter the number 5:50

Total=150

11. NULL POINTER

A Pointer is said to be a null pointer when its right value is 0.

Example:

int *a;

int *b;

b=a=0;

12. POINTERS TO POINTERS

In general, pointer is a variable that contains the address of another variable. Similarly,
another pointer variable can store the address of this pointer variable. This is a pointer to
pointer variable.
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

Pictorial Representation

Note:

 ‘p1′ is the address of ‘p2′ ie 5000


 ‘*p1′ is the value held by ‘p2′ ie 8000
 ‘**p1′ is the value at 8000 ie ‘c’

Example:

int a=20;

int *b;

int **c;

b=&a;

c=&b;

Program:

#include<stdio.h>

main()

int a=20, int *b;

int **c;

b=&a;

c=&b;
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

printf(“Value of a is %d\n”,a);

printf(“Value of a is %d\n”,*(&a));

printf(“Value of a is %d\n”,*b);

printf(“Value of a is %d\n”,**c);

printf(“Value of b and address of a=%u\n”,b);

printf(“Address of a is %u”,&a);

printf(“Address of b is %u”,&b);

printf(“Address of a is %u”,*c);

printf(“Address of b is %u”,&b);

printf(“Address of b is %u”,c);

printf(“Address of c is %u”,&c);

getch();

Output:

Value of a is 20

Value of a is 20

Value of a is 20

Value of a is 20

Value of b and address of a=2005

Address of a is 2005

Address of b is 2005

Address of a is 2005

Address of b is 2005

Address of b is 2005

Address of c is 2005

POINTERS AND STRINGS

A character pointer is a pointer to the character. It can be declared as

Syntax:
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

char *pointer_character;

A character pointer can also be used to access character arrays and string constants, in
the same way as accessing numeric arrays using their respective pointer variable.

13. POINTER EXPRESSIONS

Pointer variables can be used in expressions. As a user, we can use integer for addition and
subtraction from pointers.

Here, the pointers are preceded by the * symbol (Indirection Operator).

Example:

(i) c=*a+*b; it can be written as c=(*a)+(*b);


(ii) s=20*-*a/*b; it can be written as s=(20*(-(*a)))/(*b);
(iii) *p=*a**b; it can be written as *p=(*a)**b;
(iv)*a=*a+15; it can be written as (*a)+=15;

Another Example:

*++c; it is interpreted as *(++c);

*c++; it is interpreted as *(c++);

d=*(c++); it is equivalent to d=*c; c=c+1;

4.POINTERS AND FUNCTIONS

The Pointer can be used as an argument in functions. The arguments (or) parameters to the
function are passed in two ways. They are given below.

(i) Call by value.


(ii) Call by reference.
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

In the above two method, especially ‘call by reference’ is used to achieve the technique of
‘Pointers and Functions’

POINTERS AND FUNCTION ARGUMENTS

 The calling function sends the addresses of the variables and the called function must
declare those incoming arguments as pointers.
 In order to modify the variables sent by the caller, the called function must dereference
the pointers that were passed to it.
 Thus, passing pointers to a function avoid the overhead of copying data from one
function to another.
 This Process is otherwise called as Call by reference.

Program ( APR/MAY 2015,MAY/JUNE 2014)

#include<stdio.h>
#include<conio.h>

void swap(int *,int *);


void main( )
{
int x,y;
clrscr();
printf("Enter the values of a & b\n");
scanf("%d%d",&a,&b);
swap(&a,&b);
printf("A=%d \n B=%d",a,b);
getch( );
}
void swap(int *px,int *py)
{
int pz;
pz=*px;
*px=*py;
*py=pz;
}
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

15: POINTER AND STRUCTURE


Univ. Ques. Jan 2014

Pointer which point structure in the same way as used with the other variable are called
Structure pointers.

General Form struct tag

member1;

member2;

………………

………………

membern;

};

struct tag*ptrvar;

Description tag - name to structure.

ptrvar - pointer variable.

() - Members of structure are accessed using the Arrow Operator.

Example: struct book_list

char book_name;

int pages;

float price;

};

struct book_list*ptr;

Example:

Program to declare pointer to structure and display the contents of the


structure
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

#include<stdio.h>
#include<conio.h>
main()
{
struct book
{
char name[25];
char author[25];
int pages;
};
struct book b1={“Computer Programming”, “Kamthane”, 479};
struct book 8ptr;
ptr=&b1;
clrscr();
printf{“\n %s by %s of %d pages”, b1.name, b1.author, b1.pages};
printf{“\n %s by %s of %d pages”, ptr->name, ptr->author, ptr->pages};

OUTPUT:
Computer Programming by Kamthane of 479 pages

Computer Programming by Kamthane of 479 pages

16. C Pointer To Strings


A String is a sequence of characters stored in an array. A string always ends with null ('\0')
character. Simply a group of characters forms a string and a group of strings form a sentence. A
pointer to array of characters or string can be looks like the following:
Sri ManakulaVinayagar Engineering College, Puducherry U23CSTC01 –Programming in C

Example
#include <stdio.h>
int main()
{
char *cities[] = {"Iran", "Iraq"};
int i;
for(i = 0; i < 2; i++)
printf("%s\n", cities[i]);
return 0;
}

Output
Iran
Iraq

In the above pointer to string program, we d eclared a pointer array of


character datatypes and then few strings like "Iran", "Iraq" where initialized to the
pointer array (*cities[]). Note that we have not declared the size of the array as it is
of character pointer type. Coming to the explanation, cities[] is an array which has its
own address and it holds the address of first element (I (Iran) ) in it as a value. This
address is then executed by the pointer, i.e) pointer start reading the value from the
address stored in the array cities[0] and end s with '\0' by default. Next cities[1]
holds the address of (I (Iraq).This address is then executed by the pointer, i.e)
pointer start reading the value from the address stored in the array cities[1] and
ends with '\0' by default. As a result Iran and Iraq is outputted.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy