Structures, Pointers and Files in C
Structures, Pointers and Files in C
Example
Example
#include <stdio.h>
void display(int,float);
void main() {
struct account
{
int accno;
float bal;
};
struct account a = {100,25000};
display(a.accno, a.bal); }
void display(int no, float balance) {
printf(“Account no :%d Balance : %f ”, no,
balance); }
#include <stdio.h>
void display(int,float);
void main()
{
struct account
{
int accno;
float bal;
};
struct account a = {100,25000};
display(a.accno, a.bal);
}
void display(int no, float balance)
{
printf(“Account no :%d Balance : %f ”, no,
balance); }
b. Passing the entire structure
When a structure is passed to a function, the
transfer is by value. i.e., the values will be copied
in a local structure and if any of the structure
variables are altered inside the function, the
changes will not be recognized in the calling
function. If we need the changes, the entire
structure has to be returned from the function.
Also we have to specify the type of the formal
parameters and return type.
#include <stdio.h>
void display (struct distance);
struct distance sum(struct distance, struct
distance);
void main( ) {
struct distance
{
int feet;
int inch;
}d1, d2, d3;
printf(“Enter 2 distances: feet & inch \n”);
scanf(“%d %d”,&d1.feet, d1.inch);
scanf(“%d %d”,&d2.feet, d2.inch);
printf(“Distance l is”)
display(d1); /* pass the structure
variable d1 */
printf(“Distance 2 is”);
display(d2); /* pass the structure
variable d2 */
d3 = sum(d1,d2);
printf(“Sum is \n”);
display(d3);
}
void display(struct distance d)
{
printf(“Feet : %d Inches %d \n”, d.feet, d.inch);
}
struct distance sum(struct distance dist1, struct
distance dist2)
{
struct distance dist3;
dist3.feet = dist1.feet + dist2.feet;
dist3.inch = dist1.inch + dist2.inch;
return dist3;
}
c. Passing the address of a structure
The address of a structure variable or member can
be passed as arguments using pointers. A structure
passed in this manner is said to be passed by
reference. Hence, if any of the structure members
are altered within the function, the changes will be
recognized in the calling function. Using the
pointer to the structure, the members of the
structure can be accessed with ->operator
#include <stdio.h>
struct distance
{
int feet;
int inch;
};
void increment(struct distance *);
void main( )
{
struct distance d = {10,1};
printf(“Before increment : %d %d”, d.feet, d.inch);
increment (&d);
printf(“After increment :%d %d”, d.feet, d.inch);
}
void increment(struct distance *dist)
{
(dist->feet)++;
(dist->inch)++;
}
Self-referential structures
If a member of a structure is a pointer to itself,
then it is said to be self-referential structures. Self
referential structures are very useful in
applications that involve linked data structures.
The general form is
struct tag
{
member 1;
member 2;
…………
struct tag *ptrname; /* pointer to itself */
};
where
void main()
{
struct stu
{
int rollno;
char name[20];
struct stu *ptr;
};
struct stu s1={111,”AAA”};
struct stu s2={222,”CCC”};
ptr=&s1;
s1.ptr=s2;
s2.ptr=NULL;
printf(“%d%S”,ptr->rollno, ptr->name);
printf(“%d%S”,s1.ptr->rollno, s1.ptr->name);
POINTERS in C
Pointers
A pointer is a variable that contains the address
of a data item such as a variable or an array
element. When it contains the address of an item,
it is said to point that item.
Significance of pointers
Basis of dynamic allocation of memory
very efficient method of accessing data.
Pointers are closely related with arrays and
hence they provide efficient techniques for
manipulating data in arrays
Used in functions as Pass-by-address
parameters.
Provide a convenient way to return multiple
data items from a function via function
Pointer Declaration
Like all other variables, pointer variables must be
declared before usage. The rules for naming the
pointer variables are same as identifiers. The
general form is
data-type *ptrvar;
where ptrvar is the name of the pointer variable
and data-type refers to the data type of the item
whose address is stored in the pointer ptrvar. The
asterisk (*) tells that the variable ptrvar is a
pointer variable.
Example int *p; /* pointer to an integer
variable*/
float *q; /* pointer to a float variable*/
Now p and q are declared as pointers which can
Size of pointer variable
The size of a pointer variable is 2 bytes irrespective
of the data type pointed by the pointer.
Example void main()
{
int *a;
float *b;
char *c;
printf("Size of the Integer pointer = %d\
n",sizeof(a));
printf("Size of the float pointer = %d\
n",sizeof(b));
printf("Size of the char pointer = %d\
n",sizeof(c));
Accessing pointer variables involve with two
operators:
a. Address operator (&)
b. Indirection or dereferencing operator (*)
a. Address operator (&)
This operator is used to obtain the address of a
variable. This operator may precede a variable
name or an array element but should not be used
before a constant or an expression. i.e. &5,
&(a+3) and &(4+i) are all invalid.
Example
/* Program for accessing variables through
pointers*/
#include <stdio.h>
void main()
{
int a = 3;
int *ptr; /* integer pointer */
ptr = &a; /* ptr points to a */
b = * ptr;
printf("a = %d address of a = %u
"a, &a);
printf("ptr = %u *ptr = %d b = %d ", ptr, *ptr,
b);
}
Example
#include <stdio.h>
void main()
{
int a = 3;
int *ptr; /* integer pointer */
ptr = &a; /* ptr points to a */
printf("Before change: *ptr = %d a = %d \n", *ptr,
a);
*ptr = 6; /* New value for a */
printf("After change: *ptr = %d a = %d \n", *ptr, a);
*ptr = *ptr + 1; /* Note the use of *ptr
on both sides*/
printf("After increment: *ptr = %d a = %d ", *ptr,
a);
(*ptr)++; /* Remember to use ( ) to evaluate
*ptr first*/
printf("After another increment: *ptr = %d a = %d
", *ptr, a);
Initialization of pointer variables
When we start our program, all the initialized
variables will have unknown garbage values in
them. It is true for pointers also. When the
program starts, uninitialized pointers will have
some unknown values in them.
Dereferencing uninitialized pointers always
leads to run time errors. To avoid this, we must
always assign a valid address to a pointer
variable.
Example int a;
int *ptr; /* integer pointer (declaration)
*/
ptr = &a; /* ptr now has a valid address
i.e.,address of a */
/* Using same pointer for multiple variables */
#include <stdio.h>
void main( ) {
int a, b, c;
int *p; /* integer pointer */
printf("Enter 3 numbers \n");
scanf("%d %d %d", &a, &b, &c);
p=&a; /* p points to a */
printf(" a = %d ", *p);
p=&b; /* p now points to b */
printf(" b = %d ", *p);
p=&c; /* p now points to c */
printf(" c = %d ", *p);
}
Operations on Pointers
Arithmetic and logical operations can be extended
to pointer variables also, but are very limited.
Arithmetic operations
Addition can be used when one operand is a pointer
and the other is an integer. Subtraction can be used
only when both operands are pointers or when first
operand is a pointer and the second operand is an
integer.
Suppose, for example, ptr is a pointer variable that
contains the address of a variable a.
i.e, int a, *ptr;
ptr = &a;
Relational operations
Two pointer variables of same type can be
compared for equality or inequality. Also pointer
variables can be compared with NULL constant.
Hence, the following expressions are all valid.
p1<p2 p1 = = p2 ptr = = NULL p1 >=
p2
Addition of 2 pointers
Multiplication of a number with a pointer
Dividing a pointer with a number
Assigning an arbitrary address by you to the
pointer variable.
Array of Pointers
Like an array of ints and an array of chars,
there is an array of pointers as well. Such an
array would simply be a collection of
addresses. Those addresses could point to
individual variables or another array as well.
dataType *variableName[size];
/* Examples */
int *a[5];
char *c[8];
int main()
{
int a,b,c;
int *ptr[3];
ptr[0]= &a;
ptr[1]= &b;
ptr[2]= &c;
a=100;
b=200;
c=300;
printf("value of a: %d, b: %d, c: d\
n",*ptr[0],*ptr[1],*ptr[2]);
*ptr[0] +=10;
*ptr[1] +=10;
*ptr[2] +=10;
printf("After adding 10\nvalue of a: %d, b: %d,
c: %d\n",*ptr[0],*ptr[1],*ptr[2]);
return 0;
}
Pointer to an Array
name
Pointer: It contains the address of an aother variable
int *p;
p=a; // pointer p points to the starting address of an
array.
Traversing an array elements
*(p+i) is used to traverse the elements of
an array
where i represents the index of an
array.
Example:
*(p+0)- first element of an array
*(p+1)- second element of an array
*(p+2)- third element of an array
A Simple Program
#include <stdio.h>
int main()
{
int a[5]={10,20,30,40,50};
int *p , i;
p=a; OUTPUT
printf("The Elements of an array are \n"); The Elements of an array are
for (i=0 ; i<5;i++) 10
{ 20
printf("%d\n",*(p+i)); 30
40
}
50
return 0;
}
/* Program for pointer to an array */
int main () {
double balance[5] = {1000.0, 2.0, 3.4, 17.0,
50.0};
double *p;
float sum=0;
int i;
p = balance;
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ ) {
sum=sum+*(p+i));
}
printf("sum=%f”,sum );
}
Adavntages of Pointer over an Array
Dynamic Memory Allocation : Using pointers, we can
allocate memory dynamically to an array.
The header file used for Dynamic memory allocation is
<stdlib.h>
Functions used for dynamic memory allocation are
malloc()
calloc()
free()
realloc()
malloc() function
“malloc” or “memory allocation” is used to
dynamically allocate a single large block of memory
with the specified size.
syntax:
ptr = (cast-type*) malloc(byte-size)
Example :
ptr = (int*)malloc(n*sizeof(int));
where n can be during the runtime of the
program
size of the ptr depends on the value of n
A Simple Program - malloc()
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
calloc()
It dynamically allocates the specified number
of blocks of memory of the specified type
continuosly.
It initializes each block with a default value
‘0’.
It is called as continuous allocation method
syntax:
ptr = (cast-type*) calloc(n,byte-size);
Example :
ptr=(int*)calloc(n,sizeof(int)); It allocates
the space for n elements continously.
A Simple Program - calloc() method
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
realloc()
“realloc” or “re-allocation” method in C is used to
dynamically change the memory allocation of a
previously allocated memory. In other words, if the
memory previously allocated with the help of malloc
or calloc is insufficient, realloc can be used to
dynamically re-allocate memory.
syntax:
ptr = realloc(ptr, newSize);
Example
ptr=realloc(ptr, n* sizeof(data-type));
where n is the new size
int main()
{
int n, i, *ptr,sum=0,sum1=0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
n=n+2;
ptr=(int*) realloc(ptr,n*sizeof(int));
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum1 += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
Array of Pointers or Pointer
Arrays
Array of the pointer variables.
Syntax
int *array_name[size];